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; // > 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);
334 if (cl_netpacketloss.integer)
335 for (i = 0;i < cl_numsockets;i++)
336 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
338 if (developer_networking.integer)
340 char addressstring[128], addressstring2[128];
341 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
344 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
345 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
346 Com_HexDumpToConsole(data, length);
349 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
354 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
358 if (cl_netpacketloss.integer)
359 for (i = 0;i < cl_numsockets;i++)
360 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
362 ret = LHNET_Write(mysocket, data, length, peeraddress);
363 if (developer_networking.integer)
365 char addressstring[128], addressstring2[128];
366 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
367 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
368 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
369 Com_HexDumpToConsole(data, length);
374 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
376 // note this does not include the trailing NULL because we add that in the parser
377 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
380 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
382 unsigned int packetLen;
383 unsigned int dataLen;
385 unsigned int *header;
388 if (data->cursize == 0)
389 Sys_Error("Datagram_SendMessage: zero length message\n");
391 if (data->cursize > (int)sizeof(conn->sendMessage))
392 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
394 if (conn->canSend == false)
395 Sys_Error("SendMessage: called with canSend == false\n");
398 memcpy(conn->sendMessage, data->data, data->cursize);
399 conn->sendMessageLength = data->cursize;
401 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
403 dataLen = conn->sendMessageLength;
408 dataLen = MAX_PACKETFRAGMENT;
412 packetLen = NET_HEADERSIZE + dataLen;
414 header = (void *)sendbuffer;
415 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
416 header[1] = BigLong(conn->sendSequence);
417 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
419 conn->sendSequence++;
420 conn->canSend = false;
422 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
425 conn->lastSendTime = realtime;
427 reliableMessagesSent++;
431 static void NetConn_SendMessageNext(netconn_t *conn)
433 unsigned int packetLen;
434 unsigned int dataLen;
436 unsigned int *header;
438 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
440 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
442 dataLen = conn->sendMessageLength;
447 dataLen = MAX_PACKETFRAGMENT;
451 packetLen = NET_HEADERSIZE + dataLen;
453 header = (void *)sendbuffer;
454 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
455 header[1] = BigLong(conn->sendSequence);
456 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
458 conn->sendSequence++;
459 conn->sendNext = false;
461 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
464 conn->lastSendTime = realtime;
469 static void NetConn_ReSendMessage(netconn_t *conn)
471 unsigned int packetLen;
472 unsigned int dataLen;
474 unsigned int *header;
476 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
478 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
480 dataLen = conn->sendMessageLength;
485 dataLen = MAX_PACKETFRAGMENT;
489 packetLen = NET_HEADERSIZE + dataLen;
491 header = (void *)sendbuffer;
492 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
493 header[1] = BigLong(conn->sendSequence - 1);
494 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
496 conn->sendNext = false;
498 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
501 conn->lastSendTime = realtime;
506 qboolean NetConn_CanSendMessage(netconn_t *conn)
508 return conn->canSend;
511 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
516 packetLen = NET_HEADERSIZE + data->cursize;
519 if (data->cursize == 0)
520 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
522 if (packetLen > (int)sizeof(sendbuffer))
523 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
526 header = (void *)sendbuffer;
527 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
528 header[1] = BigLong(conn->unreliableSendSequence);
529 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
531 conn->unreliableSendSequence++;
533 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
537 unreliableMessagesSent++;
541 void NetConn_CloseClientPorts(void)
543 for (;cl_numsockets > 0;cl_numsockets--)
544 if (cl_sockets[cl_numsockets - 1])
545 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
548 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
550 lhnetaddress_t address;
552 char addressstring2[1024];
553 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
555 if ((s = LHNET_OpenSocket_Connectionless(&address)))
557 cl_sockets[cl_numsockets++] = s;
558 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
559 Con_Printf("Client opened a socket on address %s\n", addressstring2);
563 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
564 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
568 Con_Printf("Client unable to parse address %s\n", addressstring);
571 void NetConn_OpenClientPorts(void)
574 NetConn_CloseClientPorts();
575 port = bound(0, cl_netport.integer, 65535);
576 if (cl_netport.integer != port)
577 Cvar_SetValueQuick(&cl_netport, port);
578 Con_Printf("Client using port %i\n", port);
579 NetConn_OpenClientPort("local:2", 0);
580 NetConn_OpenClientPort(net_address.string, port);
581 //NetConn_OpenClientPort(net_address_ipv6.string, port);
584 void NetConn_CloseServerPorts(void)
586 for (;sv_numsockets > 0;sv_numsockets--)
587 if (sv_sockets[sv_numsockets - 1])
588 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
591 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
593 lhnetaddress_t address;
595 char addressstring2[1024];
596 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
598 if ((s = LHNET_OpenSocket_Connectionless(&address)))
600 sv_sockets[sv_numsockets++] = s;
601 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
602 Con_Printf("Server listening on address %s\n", addressstring2);
606 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
607 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
611 Con_Printf("Server unable to parse address %s\n", addressstring);
614 void NetConn_OpenServerPorts(int opennetports)
617 NetConn_CloseServerPorts();
618 port = bound(0, sv_netport.integer, 65535);
621 Con_Printf("Server using port %i\n", port);
622 if (sv_netport.integer != port)
623 Cvar_SetValueQuick(&sv_netport, port);
624 if (cls.state != ca_dedicated)
625 NetConn_OpenServerPort("local:1", 0);
628 NetConn_OpenServerPort(net_address.string, port);
629 //NetConn_OpenServerPort(net_address_ipv6.string, port);
631 if (sv_numsockets == 0)
632 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
635 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
637 int i, a = LHNETADDRESS_GetAddressType(address);
638 for (i = 0;i < cl_numsockets;i++)
639 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
640 return cl_sockets[i];
644 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
646 int i, a = LHNETADDRESS_GetAddressType(address);
647 for (i = 0;i < sv_numsockets;i++)
648 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
649 return sv_sockets[i];
653 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
656 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
657 conn->mysocket = mysocket;
658 conn->peeraddress = *peeraddress;
659 conn->canSend = true;
660 conn->lastMessageTime = realtime;
661 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
662 // reduce effectiveness of connection request floods
663 conn->timeout = realtime + net_connecttimeout.value;
664 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
665 conn->next = netconn_list;
670 void NetConn_Close(netconn_t *conn)
673 // remove connection from list
674 if (conn == netconn_list)
675 netconn_list = conn->next;
678 for (c = netconn_list;c;c = c->next)
682 c->next = conn->next;
686 // not found in list, we'll avoid crashing here...
694 static int clientport = -1;
695 static int clientport2 = -1;
696 static int hostport = -1;
697 static void NetConn_UpdateServerStuff(void)
699 if (cls.state != ca_dedicated)
701 if (clientport2 != cl_netport.integer)
703 clientport2 = cl_netport.integer;
704 if (cls.state == ca_connected)
705 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
707 if (cls.state == ca_disconnected && clientport != clientport2)
709 clientport = clientport2;
710 NetConn_CloseClientPorts();
712 if (cl_numsockets == 0)
713 NetConn_OpenClientPorts();
716 if (hostport != sv_netport.integer)
718 hostport = sv_netport.integer;
720 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
724 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
728 unsigned int sequence;
732 length = BigLong(((int *)data)[0]);
733 flags = length & ~NETFLAG_LENGTH_MASK;
734 length &= NETFLAG_LENGTH_MASK;
735 // control packets were already handled
736 if (!(flags & NETFLAG_CTL))
738 sequence = BigLong(((int *)data)[1]);
742 if (flags & NETFLAG_UNRELIABLE)
744 if (sequence >= conn->unreliableReceiveSequence)
746 if (sequence > conn->unreliableReceiveSequence)
748 count = sequence - conn->unreliableReceiveSequence;
749 droppedDatagrams += count;
750 Con_DPrintf("Dropped %u datagram(s)\n", count);
752 conn->unreliableReceiveSequence = sequence + 1;
753 conn->lastMessageTime = realtime;
754 conn->timeout = realtime + net_messagetimeout.value;
755 unreliableMessagesReceived++;
758 SZ_Clear(&net_message);
759 SZ_Write(&net_message, data, length);
765 Con_DPrint("Got a stale datagram\n");
768 else if (flags & NETFLAG_ACK)
770 if (sequence == (conn->sendSequence - 1))
772 if (sequence == conn->ackSequence)
775 if (conn->ackSequence != conn->sendSequence)
776 Con_DPrint("ack sequencing error\n");
777 conn->lastMessageTime = realtime;
778 conn->timeout = realtime + net_messagetimeout.value;
779 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
780 if (conn->sendMessageLength > 0)
782 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
783 conn->sendNext = true;
784 NetConn_SendMessageNext(conn);
788 conn->sendMessageLength = 0;
789 conn->canSend = true;
793 Con_DPrint("Duplicate ACK received\n");
796 Con_DPrint("Stale ACK received\n");
799 else if (flags & NETFLAG_DATA)
801 unsigned int temppacket[2];
802 temppacket[0] = BigLong(8 | NETFLAG_ACK);
803 temppacket[1] = BigLong(sequence);
804 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
805 if (sequence == conn->receiveSequence)
807 conn->lastMessageTime = realtime;
808 conn->timeout = realtime + net_messagetimeout.value;
809 conn->receiveSequence++;
810 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
811 conn->receiveMessageLength += length;
812 if (flags & NETFLAG_EOM)
814 reliableMessagesReceived++;
815 length = conn->receiveMessageLength;
816 conn->receiveMessageLength = 0;
819 SZ_Clear(&net_message);
820 SZ_Write(&net_message, conn->receiveMessage, length);
827 receivedDuplicateCount++;
835 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
837 cls.connect_trying = false;
838 M_Update_Return_Reason("");
839 // the connection request succeeded, stop current connection and set up a new connection
841 cls.netcon = NetConn_Open(mysocket, peeraddress);
842 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
845 cls.demonum = -1; // not in the demo loop now
846 cls.state = ca_connected;
847 cls.signon = 0; // need all the signon messages before playing
851 int NetConn_IsLocalGame(void)
853 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
858 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
861 lhnetaddress_t svaddress;
863 char *string, addressstring2[128], cname[128], ipstring[32];
864 char stringbuf[16384];
866 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
868 // received a command string - strip off the packaging and put it
869 // into our string buffer with NULL termination
872 length = min(length, (int)sizeof(stringbuf) - 1);
873 memcpy(stringbuf, data, length);
874 stringbuf[length] = 0;
877 if (developer.integer)
879 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
880 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
881 Com_HexDumpToConsole(data, length);
884 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
886 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
887 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
888 M_Update_Return_Reason("Got challenge response");
889 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
892 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
894 M_Update_Return_Reason("Accepted");
895 NetConn_ConnectionEstablished(mysocket, peeraddress);
898 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
900 char rejectreason[32];
901 cls.connect_trying = false;
903 length = max(length - 7, (int)sizeof(rejectreason) - 1);
904 memcpy(rejectreason, string, length);
905 rejectreason[length] = 0;
906 M_Update_Return_Reason(rejectreason);
909 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
911 hostcache_info_t *info;
916 // hostcache only uses text addresses
917 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
918 // search the cache for this server and update it
919 for( n = 0; n < hostcache_cachecount; n++ )
920 if( !strcmp( cname, hostcache_cache[n].info.cname ) )
922 if( n == hostcache_cachecount )
925 info = &hostcache_cache[n].info;
926 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
927 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
928 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
929 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
930 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
931 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
932 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
934 if (info->ping == 100000)
937 pingtime = (int)((realtime - hostcache_cache[n].querytime) * 1000.0);
938 pingtime = bound(0, pingtime, 9999);
940 info->ping = pingtime;
942 // legacy/old stuff move it to the menu ASAP
944 // build description strings for the things users care about
945 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);
946 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);
947 // if ping is especially high, display it as such
950 // orange numbers (lower block)
951 for (i = 0;i < 5;i++)
952 if (hostcache_cache[n].line1[i] != ' ')
953 hostcache_cache[n].line1[i] += 128;
955 else if (pingtime >= 200)
957 // yellow numbers (in upper block)
958 for (i = 0;i < 5;i++)
959 if (hostcache_cache[n].line1[i] != ' ')
960 hostcache_cache[n].line1[i] -= 30;
962 // if not in the slist menu we should print the server to console
963 if( hostcache_consoleoutput )
964 Con_Printf("%s\n%s\n", hostcache_cache[n].line1, hostcache_cache[n].line2);
965 // and finally, update the view set
966 if( hostcache_cache[n].finished )
967 _HostCache_Remove( &hostcache_cache[n] );
968 _HostCache_Insert( &hostcache_cache[n] );
969 hostcache_cache[n].finished = true;
973 if (!strncmp(string, "getserversResponse\\", 19) && hostcache_cachecount < HOSTCACHE_TOTALSIZE)
975 // Extract the IP addresses
979 if (hostcache_consoleoutput)
980 Con_Print("received server list...\n");
981 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
985 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
986 if (developer.integer)
987 Con_Printf("Requesting info from server %s\n", ipstring);
988 // ignore the rest of the message if the hostcache is full
989 if( hostcache_cachecount == HOSTCACHE_TOTALSIZE )
992 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
993 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
995 memset(&hostcache_cache[hostcache_cachecount], 0, sizeof(hostcache_cache[hostcache_cachecount]));
996 // store the data the engine cares about (address and ping)
997 strlcpy (hostcache_cache[hostcache_cachecount].info.cname, ipstring, sizeof (hostcache_cache[hostcache_cachecount].info.cname));
998 hostcache_cache[hostcache_cachecount].info.ping = 100000;
999 hostcache_cache[hostcache_cachecount].querytime = realtime;
1000 // if not in the slist menu we should print the server to console
1001 if (hostcache_consoleoutput)
1002 Con_Printf("querying %s\n", ipstring);
1004 ++hostcache_cachecount;
1006 // move on to next address in packet
1013 if (!strncmp(string, "ping", 4))
1015 if (developer.integer)
1016 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1017 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1020 if (!strncmp(string, "ack", 3))
1023 // we may not have liked the packet, but it was a command packet, so
1024 // we're done processing this packet now
1027 // netquake control packets, supported for compatibility only
1028 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1033 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1037 if (developer.integer)
1038 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1039 if (cls.connect_trying)
1041 lhnetaddress_t clientportaddress;
1042 clientportaddress = *peeraddress;
1045 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1048 LHNETADDRESS_SetPort(&clientportaddress, port);
1050 M_Update_Return_Reason("Accepted");
1051 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1055 if (developer.integer)
1056 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1057 cls.connect_trying = false;
1058 M_Update_Return_Reason(data);
1061 case CCREP_SERVER_INFO:
1062 if (developer.integer)
1063 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1064 if (cls.state != ca_dedicated)
1066 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1067 // string we just ignore it and keep the real address
1069 // hostcache only uses text addresses
1070 cname = UDP_AddrToString(readaddr);
1071 // search the cache for this server
1072 for (n = 0; n < hostCacheCount; n++)
1073 if (!strcmp(cname, hostcache[n].cname))
1076 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
1079 memset(&hostcache[n], 0, sizeof(hostcache[n]));
1080 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
1081 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
1082 hostcache[n].users = MSG_ReadByte();
1083 hostcache[n].maxusers = MSG_ReadByte();
1085 if (c != NET_PROTOCOL_VERSION)
1087 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
1088 strcpy(hostcache[n].name, "*");
1089 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
1091 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
1095 case CCREP_PLAYER_INFO:
1096 // we got a CCREP_PLAYER_INFO??
1097 //if (developer.integer)
1098 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1100 case CCREP_RULE_INFO:
1101 // we got a CCREP_RULE_INFO??
1102 //if (developer.integer)
1103 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1109 // we may not have liked the packet, but it was a valid control
1110 // packet, so we're done processing this packet now
1114 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)
1115 CL_ParseServerMessage();
1119 void NetConn_ClientFrame(void)
1122 lhnetaddress_t peeraddress;
1124 NetConn_UpdateServerStuff();
1125 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1127 if (cls.connect_remainingtries == 0)
1129 cls.connect_trying = false;
1130 M_Update_Return_Reason("Connect: Failed");
1133 cls.connect_nextsendtime = realtime + 1;
1134 cls.connect_remainingtries--;
1135 // try challenge first (newer server)
1136 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1137 // then try netquake as a fallback (old server, or netquake)
1138 SZ_Clear(&net_message);
1139 // save space for the header, filled in later
1140 MSG_WriteLong(&net_message, 0);
1141 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1142 MSG_WriteString(&net_message, "QUAKE");
1143 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1144 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1145 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1146 SZ_Clear(&net_message);
1148 for (i = 0;i < cl_numsockets;i++)
1149 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1150 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1151 if (cls.netcon && realtime > cls.netcon->timeout)
1153 Con_Print("Connection timed out\n");
1155 Host_ShutdownServer (false);
1157 for (conn = netconn_list;conn;conn = conn->next)
1158 NetConn_ReSendMessage(conn);
1161 #define MAX_CHALLENGES 128
1164 lhnetaddress_t address;
1168 challenge[MAX_CHALLENGES];
1170 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1174 for (i = 0;i < bufferlength - 1;i++)
1178 c = rand () % (127 - 33) + 33;
1179 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1185 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1187 int i, n, ret, clientnum, responselength, best;
1191 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1195 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1197 // received a command string - strip off the packaging and put it
1198 // into our string buffer with NULL termination
1201 length = min(length, (int)sizeof(stringbuf) - 1);
1202 memcpy(stringbuf, data, length);
1203 stringbuf[length] = 0;
1206 if (developer.integer)
1208 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1209 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1210 Com_HexDumpToConsole(data, length);
1213 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1215 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1217 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1219 if (besttime > challenge[i].time)
1220 besttime = challenge[best = i].time;
1222 // if we did not find an exact match, choose the oldest and
1223 // update address and string
1224 if (i == MAX_CHALLENGES)
1227 challenge[i].address = *peeraddress;
1228 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1230 challenge[i].time = realtime;
1231 // send the challenge
1232 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1235 if (length > 8 && !memcmp(string, "connect\\", 8))
1239 if ((s = SearchInfostring(string, "challenge")))
1241 // validate the challenge
1242 for (i = 0;i < MAX_CHALLENGES;i++)
1243 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1245 if (i < MAX_CHALLENGES)
1247 // check engine protocol
1248 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1250 if (developer.integer)
1251 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1252 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1256 // see if this is a duplicate connection request
1257 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1258 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1260 if (clientnum < svs.maxclients)
1262 // duplicate connection request
1263 if (realtime - client->connecttime < 2.0)
1265 // client is still trying to connect,
1266 // so we send a duplicate reply
1267 if (developer.integer)
1268 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1269 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1271 // only kick if old connection seems dead
1272 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1274 // kick off connection and await retry
1275 client->deadsocket = true;
1280 // this is a new client, find a slot
1281 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1282 if (!client->active)
1284 if (clientnum < svs.maxclients)
1286 // prepare the client struct
1287 if ((conn = NetConn_Open(mysocket, peeraddress)))
1289 // allocated connection
1290 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1291 if (developer.integer)
1292 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1293 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1294 // now set up the client
1295 SV_ConnectClient(clientnum, conn);
1296 NetConn_Heartbeat(1);
1302 if (developer.integer)
1303 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1304 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1312 if (length >= 7 && !memcmp(string, "getinfo", 7))
1314 const char *challenge = NULL;
1315 // If there was a challenge in the getinfo message
1316 if (length > 8 && string[7] == ' ')
1317 challenge = string + 8;
1318 for (i = 0, n = 0;i < svs.maxclients;i++)
1319 if (svs.clients[i].active)
1321 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1322 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1323 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1324 gamename, com_modname, svs.maxclients, n,
1325 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1326 // does it fit in the buffer?
1327 if (responselength < (int)sizeof(response))
1329 if (developer.integer)
1330 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1331 NetConn_WriteString(mysocket, response, peeraddress);
1336 if (!strncmp(string, "ping", 4))
1338 if (developer.integer)
1339 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1340 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1343 if (!strncmp(string, "ack", 3))
1346 // we may not have liked the packet, but it was a command packet, so
1347 // we're done processing this packet now
1350 // LordHavoc: disabled netquake control packet support in server
1354 // netquake control packets, supported for compatibility only
1355 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1360 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1364 //if (developer.integer)
1365 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1366 if (length >= (int)strlen("QUAKE") + 1 + 1)
1368 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1370 if (developer.integer)
1371 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1372 SZ_Clear(&net_message);
1373 // save space for the header, filled in later
1374 MSG_WriteLong(&net_message, 0);
1375 MSG_WriteByte(&net_message, CCREP_REJECT);
1376 MSG_WriteString(&net_message, "Incompatible version.\n");
1377 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1378 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1379 SZ_Clear(&net_message);
1383 // see if this is a duplicate connection request
1384 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1385 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1387 if (clientnum < svs.maxclients)
1389 // duplicate connection request
1390 if (realtime - client->connecttime < 2.0)
1392 // client is still trying to connect,
1393 // so we send a duplicate reply
1394 if (developer.integer)
1395 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1396 SZ_Clear(&net_message);
1397 // save space for the header, filled in later
1398 MSG_WriteLong(&net_message, 0);
1399 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1400 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1401 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1402 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1403 SZ_Clear(&net_message);
1405 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1407 // the old client hasn't sent us anything
1408 // in quite a while, so kick off and let
1409 // the retry take care of it...
1410 client->deadsocket = true;
1415 // this is a new client, find a slot
1416 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1417 if (!client->active)
1419 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1421 // connect to the client
1422 // everything is allocated, just fill in the details
1423 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1424 if (developer.integer)
1425 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1426 // send back the info about the server connection
1427 SZ_Clear(&net_message);
1428 // save space for the header, filled in later
1429 MSG_WriteLong(&net_message, 0);
1430 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1431 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1432 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1433 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1434 SZ_Clear(&net_message);
1435 // now set up the client struct
1436 SV_ConnectClient(clientnum, conn);
1437 NetConn_Heartbeat(1);
1441 //if (developer.integer)
1442 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1443 // no room; try to let player know
1444 SZ_Clear(&net_message);
1445 // save space for the header, filled in later
1446 MSG_WriteLong(&net_message, 0);
1447 MSG_WriteByte(&net_message, CCREP_REJECT);
1448 MSG_WriteString(&net_message, "Server is full.\n");
1449 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1450 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1451 SZ_Clear(&net_message);
1458 case CCREQ_SERVER_INFO:
1459 if (developer.integer)
1460 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1461 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1463 if (developer.integer)
1464 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1465 SZ_Clear(&net_message);
1466 // save space for the header, filled in later
1467 MSG_WriteLong(&net_message, 0);
1468 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1469 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1470 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1471 MSG_WriteString(&net_message, hostname.string);
1472 MSG_WriteString(&net_message, sv.name);
1473 MSG_WriteByte(&net_message, net_activeconnections);
1474 MSG_WriteByte(&net_message, svs.maxclients);
1475 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1476 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1477 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1478 SZ_Clear(&net_message);
1481 case CCREQ_PLAYER_INFO:
1482 if (developer.integer)
1483 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1486 int playerNumber, activeNumber, clientNumber;
1489 playerNumber = MSG_ReadByte();
1491 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1492 if (client->active && ++activeNumber == playerNumber)
1494 if (clientNumber != svs.maxclients)
1496 SZ_Clear(&net_message);
1497 // save space for the header, filled in later
1498 MSG_WriteLong(&net_message, 0);
1499 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1500 MSG_WriteByte(&net_message, playerNumber);
1501 MSG_WriteString(&net_message, client->name);
1502 MSG_WriteLong(&net_message, client->colors);
1503 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1504 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1505 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1506 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1507 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1508 SZ_Clear(&net_message);
1512 case CCREQ_RULE_INFO:
1513 if (developer.integer)
1514 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1520 // find the search start location
1521 prevCvarName = MSG_ReadString();
1522 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1524 // send the response
1525 SZ_Clear(&net_message);
1526 // save space for the header, filled in later
1527 MSG_WriteLong(&net_message, 0);
1528 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1531 MSG_WriteString(&net_message, var->name);
1532 MSG_WriteString(&net_message, var->string);
1534 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1535 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1536 SZ_Clear(&net_message);
1543 // we may not have liked the packet, but it was a valid control
1544 // packet, so we're done processing this packet now
1549 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1551 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1553 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1554 SV_ReadClientMessage();
1562 void NetConn_ServerFrame(void)
1565 lhnetaddress_t peeraddress;
1567 NetConn_UpdateServerStuff();
1568 for (i = 0;i < sv_numsockets;i++)
1569 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1570 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1571 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1573 // never timeout loopback connections
1574 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1576 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1577 SV_DropClient(false);
1580 for (conn = netconn_list;conn;conn = conn->next)
1581 NetConn_ReSendMessage(conn);
1584 void NetConn_QueryMasters(void)
1588 lhnetaddress_t masteraddress;
1591 if (hostcache_cachecount >= HOSTCACHE_TOTALSIZE)
1594 for (i = 0;i < cl_numsockets;i++)
1601 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1603 SZ_Clear(&net_message);
1604 // save space for the header, filled in later
1605 MSG_WriteLong(&net_message, 0);
1606 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1607 MSG_WriteString(&net_message, "QUAKE");
1608 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1609 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1610 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1611 SZ_Clear(&net_message);
1615 // build the getservers
1616 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1619 for (masternum = 0;sv_masters[masternum].name;masternum++)
1621 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1624 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1629 if (!masterquerycount)
1631 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1632 M_Update_Return_Reason("No network");
1636 void NetConn_Heartbeat(int priority)
1638 lhnetaddress_t masteraddress;
1640 lhnetsocket_t *mysocket;
1642 // if it's a state change (client connected), limit next heartbeat to no
1643 // more than 30 sec in the future
1644 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1645 nextheartbeattime = realtime + 30.0;
1647 // limit heartbeatperiod to 30 to 270 second range,
1648 // lower limit is to avoid abusing master servers with excess traffic,
1649 // upper limit is to avoid timing out on the master server (which uses
1651 if (sv_heartbeatperiod.value < 30)
1652 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1653 if (sv_heartbeatperiod.value > 270)
1654 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1656 // make advertising optional and don't advertise singleplayer games, and
1657 // only send a heartbeat as often as the admin wants
1658 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1660 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1661 for (masternum = 0;sv_masters[masternum].name;masternum++)
1662 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1663 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1667 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1670 qbyte sent[MAX_SCOREBOARD];
1672 memset(sent, 0, sizeof(sent));
1674 // simultaneously wait for the first CanSendMessage and send the message,
1675 // then wait for a second CanSendMessage (verifying it was received), or
1676 // the client drops and is no longer counted
1677 // the loop aborts when either it runs out of clients to send to, or a
1679 blocktime += Sys_DoubleTime();
1683 NetConn_ClientFrame();
1684 NetConn_ServerFrame();
1685 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1687 if (host_client->netconnection)
1689 if (NetConn_CanSendMessage(host_client->netconnection))
1692 NetConn_SendReliableMessage(host_client->netconnection, data);
1695 if (!NetConn_CanSendMessage(host_client->netconnection))
1700 while (count && Sys_DoubleTime() < blocktime);
1704 static void Net_Heartbeat_f(void)
1707 NetConn_Heartbeat(2);
1709 Con_Print("No server running, can not heartbeat to master server.\n");
1712 void PrintStats(netconn_t *conn)
1714 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1717 void Net_Stats_f(void)
1720 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1721 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1722 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1723 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1724 Con_Printf("packetsSent = %i\n", packetsSent);
1725 Con_Printf("packetsReSent = %i\n", packetsReSent);
1726 Con_Printf("packetsReceived = %i\n", packetsReceived);
1727 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1728 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1729 Con_Print("connections =\n");
1730 for (conn = netconn_list;conn;conn = conn->next)
1734 void Net_Slist_f(void)
1736 HostCache_ResetMasks();
1737 hostcache_sortbyfield = HCIF_PING;
1738 hostcache_sortdescending = false;
1739 if (m_state != m_slist) {
1740 Con_Print("Sending requests to master servers\n");
1741 HostCache_QueryList();
1742 hostcache_consoleoutput = true;
1743 Con_Print("Listening for replies...\n");
1745 HostCache_QueryList();
1748 void NetConn_Init(void)
1751 lhnetaddress_t tempaddress;
1752 netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1753 Cmd_AddCommand("net_stats", Net_Stats_f);
1754 Cmd_AddCommand("net_slist", Net_Slist_f);
1755 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1756 Cvar_RegisterVariable(&net_messagetimeout);
1757 Cvar_RegisterVariable(&net_messagerejointimeout);
1758 Cvar_RegisterVariable(&net_connecttimeout);
1759 Cvar_RegisterVariable(&cl_netlocalping);
1760 Cvar_RegisterVariable(&cl_netpacketloss);
1761 Cvar_RegisterVariable(&hostname);
1762 Cvar_RegisterVariable(&developer_networking);
1763 Cvar_RegisterVariable(&cl_netport);
1764 Cvar_RegisterVariable(&sv_netport);
1765 Cvar_RegisterVariable(&net_address);
1766 //Cvar_RegisterVariable(&net_address_ipv6);
1767 Cvar_RegisterVariable(&sv_public);
1768 Cvar_RegisterVariable(&sv_heartbeatperiod);
1769 for (i = 0;sv_masters[i].name;i++)
1770 Cvar_RegisterVariable(&sv_masters[i]);
1771 // 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.
1772 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1774 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1776 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1777 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1780 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1782 // 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
1783 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1785 i = atoi(com_argv[i + 1]);
1786 if (i >= 0 && i < 65536)
1788 Con_Printf("-port option used, setting port cvar to %i\n", i);
1789 Cvar_SetValueQuick(&sv_netport, i);
1792 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1796 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1800 void NetConn_Shutdown(void)
1802 NetConn_CloseClientPorts();
1803 NetConn_CloseServerPorts();