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 *A && !!strstr( B, A ); // we want a real bool
174 else if( op == HCMO_NOTCONTAIN )
175 return !*A || !strstr( B, A );
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_andmasks, 0, sizeof( hostcache_andmasks ) );
296 void HostCache_QueryList(void)
298 masterquerytime = realtime;
299 masterquerycount = 0;
300 masterreplycount = 0;
301 serverquerycount = 0;
302 serverreplycount = 0;
303 hostcache_cachecount = 0;
304 hostcache_viewcount = 0;
305 hostcache_consoleoutput = false;
306 NetConn_QueryMasters();
310 static void _HostCache_PingTest(void)
313 for( i = 0 ; i < 50 ; i++ ) {
314 memset( &hostcache_cache[hostcache_cachecount], 0, sizeof( hostcache_t ) );
315 hostcache_cache[hostcache_cachecount].info.ping = rand() % 450;
316 hostcache_cache[hostcache_cachecount].finished = true;
317 sprintf( hostcache_cache[hostcache_cachecount].line1, "%i", hostcache_cache[hostcache_cachecount].info.ping );
318 _HostCache_Insert( &hostcache_cache[hostcache_cachecount] );
319 hostcache_cachecount++;
326 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
328 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
330 if (cl_netpacketloss.integer)
331 for (i = 0;i < cl_numsockets;i++)
332 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
334 if (developer_networking.integer && length != 0)
336 char addressstring[128], addressstring2[128];
337 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
340 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
341 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
342 Com_HexDumpToConsole(data, length);
345 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
350 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
354 if (cl_netpacketloss.integer)
355 for (i = 0;i < cl_numsockets;i++)
356 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
358 ret = LHNET_Write(mysocket, data, length, peeraddress);
359 if (developer_networking.integer)
361 char addressstring[128], addressstring2[128];
362 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
363 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
364 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
365 Com_HexDumpToConsole(data, length);
370 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
372 // note this does not include the trailing NULL because we add that in the parser
373 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
376 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
378 unsigned int packetLen;
379 unsigned int dataLen;
381 unsigned int *header;
384 if (data->cursize == 0)
385 Sys_Error("Datagram_SendMessage: zero length message\n");
387 if (data->cursize > (int)sizeof(conn->sendMessage))
388 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
390 if (conn->canSend == false)
391 Sys_Error("SendMessage: called with canSend == false\n");
394 memcpy(conn->sendMessage, data->data, data->cursize);
395 conn->sendMessageLength = data->cursize;
397 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
399 dataLen = conn->sendMessageLength;
404 dataLen = MAX_PACKETFRAGMENT;
408 packetLen = NET_HEADERSIZE + dataLen;
410 header = (void *)sendbuffer;
411 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
412 header[1] = BigLong(conn->sendSequence);
413 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
415 conn->sendSequence++;
416 conn->canSend = false;
418 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
421 conn->lastSendTime = realtime;
423 reliableMessagesSent++;
427 static void NetConn_SendMessageNext(netconn_t *conn)
429 unsigned int packetLen;
430 unsigned int dataLen;
432 unsigned int *header;
434 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
436 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
438 dataLen = conn->sendMessageLength;
443 dataLen = MAX_PACKETFRAGMENT;
447 packetLen = NET_HEADERSIZE + dataLen;
449 header = (void *)sendbuffer;
450 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
451 header[1] = BigLong(conn->sendSequence);
452 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
454 conn->sendSequence++;
455 conn->sendNext = false;
457 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
460 conn->lastSendTime = realtime;
465 static void NetConn_ReSendMessage(netconn_t *conn)
467 unsigned int packetLen;
468 unsigned int dataLen;
470 unsigned int *header;
472 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
474 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
476 dataLen = conn->sendMessageLength;
481 dataLen = MAX_PACKETFRAGMENT;
485 packetLen = NET_HEADERSIZE + dataLen;
487 header = (void *)sendbuffer;
488 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
489 header[1] = BigLong(conn->sendSequence - 1);
490 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
492 conn->sendNext = false;
494 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
497 conn->lastSendTime = realtime;
502 qboolean NetConn_CanSendMessage(netconn_t *conn)
504 return conn->canSend;
507 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
512 packetLen = NET_HEADERSIZE + data->cursize;
515 if (data->cursize == 0)
516 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
518 if (packetLen > (int)sizeof(sendbuffer))
519 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
522 header = (void *)sendbuffer;
523 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
524 header[1] = BigLong(conn->unreliableSendSequence);
525 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
527 conn->unreliableSendSequence++;
529 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
533 unreliableMessagesSent++;
537 void NetConn_CloseClientPorts(void)
539 for (;cl_numsockets > 0;cl_numsockets--)
540 if (cl_sockets[cl_numsockets - 1])
541 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
544 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
546 lhnetaddress_t address;
548 char addressstring2[1024];
549 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
551 if ((s = LHNET_OpenSocket_Connectionless(&address)))
553 cl_sockets[cl_numsockets++] = s;
554 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
555 Con_Printf("Client opened a socket on address %s\n", addressstring2);
559 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
560 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
564 Con_Printf("Client unable to parse address %s\n", addressstring);
567 void NetConn_OpenClientPorts(void)
570 NetConn_CloseClientPorts();
571 port = bound(0, cl_netport.integer, 65535);
572 if (cl_netport.integer != port)
573 Cvar_SetValueQuick(&cl_netport, port);
574 Con_Printf("Client using port %i\n", port);
575 NetConn_OpenClientPort("local:2", 0);
576 NetConn_OpenClientPort(net_address.string, port);
577 //NetConn_OpenClientPort(net_address_ipv6.string, port);
580 void NetConn_CloseServerPorts(void)
582 for (;sv_numsockets > 0;sv_numsockets--)
583 if (sv_sockets[sv_numsockets - 1])
584 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
587 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
589 lhnetaddress_t address;
591 char addressstring2[1024];
592 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
594 if ((s = LHNET_OpenSocket_Connectionless(&address)))
596 sv_sockets[sv_numsockets++] = s;
597 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
598 Con_Printf("Server listening on address %s\n", addressstring2);
602 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
603 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
607 Con_Printf("Server unable to parse address %s\n", addressstring);
610 void NetConn_OpenServerPorts(int opennetports)
613 NetConn_CloseServerPorts();
614 port = bound(0, sv_netport.integer, 65535);
617 Con_Printf("Server using port %i\n", port);
618 if (sv_netport.integer != port)
619 Cvar_SetValueQuick(&sv_netport, port);
620 if (cls.state != ca_dedicated)
621 NetConn_OpenServerPort("local:1", 0);
624 NetConn_OpenServerPort(net_address.string, port);
625 //NetConn_OpenServerPort(net_address_ipv6.string, port);
627 if (sv_numsockets == 0)
628 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
631 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
633 int i, a = LHNETADDRESS_GetAddressType(address);
634 for (i = 0;i < cl_numsockets;i++)
635 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
636 return cl_sockets[i];
640 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
642 int i, a = LHNETADDRESS_GetAddressType(address);
643 for (i = 0;i < sv_numsockets;i++)
644 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
645 return sv_sockets[i];
649 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
652 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
653 conn->mysocket = mysocket;
654 conn->peeraddress = *peeraddress;
655 conn->canSend = true;
656 conn->lastMessageTime = realtime;
657 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
658 // reduce effectiveness of connection request floods
659 conn->timeout = realtime + net_connecttimeout.value;
660 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
661 conn->next = netconn_list;
666 void NetConn_Close(netconn_t *conn)
669 // remove connection from list
670 if (conn == netconn_list)
671 netconn_list = conn->next;
674 for (c = netconn_list;c;c = c->next)
678 c->next = conn->next;
682 // not found in list, we'll avoid crashing here...
690 static int clientport = -1;
691 static int clientport2 = -1;
692 static int hostport = -1;
693 static void NetConn_UpdateServerStuff(void)
695 if (cls.state != ca_dedicated)
697 if (clientport2 != cl_netport.integer)
699 clientport2 = cl_netport.integer;
700 if (cls.state == ca_connected)
701 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
703 if (cls.state == ca_disconnected && clientport != clientport2)
705 clientport = clientport2;
706 NetConn_CloseClientPorts();
708 if (cl_numsockets == 0)
709 NetConn_OpenClientPorts();
712 if (hostport != sv_netport.integer)
714 hostport = sv_netport.integer;
716 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
720 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
724 unsigned int sequence;
728 length = BigLong(((int *)data)[0]);
729 flags = length & ~NETFLAG_LENGTH_MASK;
730 length &= NETFLAG_LENGTH_MASK;
731 // control packets were already handled
732 if (!(flags & NETFLAG_CTL))
734 sequence = BigLong(((int *)data)[1]);
738 if (flags & NETFLAG_UNRELIABLE)
740 if (sequence >= conn->unreliableReceiveSequence)
742 if (sequence > conn->unreliableReceiveSequence)
744 count = sequence - conn->unreliableReceiveSequence;
745 droppedDatagrams += count;
746 Con_DPrintf("Dropped %u datagram(s)\n", count);
748 conn->unreliableReceiveSequence = sequence + 1;
749 conn->lastMessageTime = realtime;
750 conn->timeout = realtime + net_messagetimeout.value;
751 unreliableMessagesReceived++;
754 SZ_Clear(&net_message);
755 SZ_Write(&net_message, data, length);
761 Con_DPrint("Got a stale datagram\n");
764 else if (flags & NETFLAG_ACK)
766 if (sequence == (conn->sendSequence - 1))
768 if (sequence == conn->ackSequence)
771 if (conn->ackSequence != conn->sendSequence)
772 Con_DPrint("ack sequencing error\n");
773 conn->lastMessageTime = realtime;
774 conn->timeout = realtime + net_messagetimeout.value;
775 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
776 if (conn->sendMessageLength > 0)
778 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
779 conn->sendNext = true;
780 NetConn_SendMessageNext(conn);
784 conn->sendMessageLength = 0;
785 conn->canSend = true;
789 Con_DPrint("Duplicate ACK received\n");
792 Con_DPrint("Stale ACK received\n");
795 else if (flags & NETFLAG_DATA)
797 unsigned int temppacket[2];
798 temppacket[0] = BigLong(8 | NETFLAG_ACK);
799 temppacket[1] = BigLong(sequence);
800 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
801 if (sequence == conn->receiveSequence)
803 conn->lastMessageTime = realtime;
804 conn->timeout = realtime + net_messagetimeout.value;
805 conn->receiveSequence++;
806 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
807 conn->receiveMessageLength += length;
808 if (flags & NETFLAG_EOM)
810 reliableMessagesReceived++;
811 length = conn->receiveMessageLength;
812 conn->receiveMessageLength = 0;
815 SZ_Clear(&net_message);
816 SZ_Write(&net_message, conn->receiveMessage, length);
823 receivedDuplicateCount++;
831 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
833 cls.connect_trying = false;
834 M_Update_Return_Reason("");
835 // the connection request succeeded, stop current connection and set up a new connection
837 cls.netcon = NetConn_Open(mysocket, peeraddress);
838 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
841 cls.demonum = -1; // not in the demo loop now
842 cls.state = ca_connected;
843 cls.signon = 0; // need all the signon messages before playing
845 SCR_BeginLoadingPlaque();
848 int NetConn_IsLocalGame(void)
850 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
855 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
858 lhnetaddress_t svaddress;
860 char *string, addressstring2[128], cname[128], ipstring[32];
861 char stringbuf[16384];
863 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
865 // received a command string - strip off the packaging and put it
866 // into our string buffer with NULL termination
869 length = min(length, (int)sizeof(stringbuf) - 1);
870 memcpy(stringbuf, data, length);
871 stringbuf[length] = 0;
874 if (developer.integer)
876 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
877 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
878 Com_HexDumpToConsole(data, length);
881 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
883 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
884 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
885 M_Update_Return_Reason("Got challenge response");
886 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
889 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
891 M_Update_Return_Reason("Accepted");
892 NetConn_ConnectionEstablished(mysocket, peeraddress);
895 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
897 char rejectreason[32];
898 cls.connect_trying = false;
900 length = max(length - 7, (int)sizeof(rejectreason) - 1);
901 memcpy(rejectreason, string, length);
902 rejectreason[length] = 0;
903 M_Update_Return_Reason(rejectreason);
906 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
908 hostcache_info_t *info;
913 // hostcache only uses text addresses
914 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
915 // search the cache for this server and update it
916 for( n = 0; n < hostcache_cachecount; n++ )
917 if( !strcmp( cname, hostcache_cache[n].info.cname ) )
919 if( n == hostcache_cachecount )
922 info = &hostcache_cache[n].info;
923 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
924 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
925 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
926 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
927 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
928 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
929 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
931 if (info->ping == 100000)
934 pingtime = (int)((realtime - hostcache_cache[n].querytime) * 1000.0);
935 pingtime = bound(0, pingtime, 9999);
937 info->ping = pingtime;
939 // legacy/old stuff move it to the menu ASAP
941 // build description strings for the things users care about
942 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);
943 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);
944 // if ping is especially high, display it as such
947 // orange numbers (lower block)
948 for (i = 0;i < 5;i++)
949 if (hostcache_cache[n].line1[i] != ' ')
950 hostcache_cache[n].line1[i] += 128;
952 else if (pingtime >= 200)
954 // yellow numbers (in upper block)
955 for (i = 0;i < 5;i++)
956 if (hostcache_cache[n].line1[i] != ' ')
957 hostcache_cache[n].line1[i] -= 30;
959 // if not in the slist menu we should print the server to console
960 if( hostcache_consoleoutput )
961 Con_Printf("%s\n%s\n", hostcache_cache[n].line1, hostcache_cache[n].line2);
962 // and finally, update the view set
963 if( hostcache_cache[n].finished )
964 _HostCache_Remove( &hostcache_cache[n] );
965 _HostCache_Insert( &hostcache_cache[n] );
966 hostcache_cache[n].finished = true;
970 if (!strncmp(string, "getserversResponse\\", 19) && hostcache_cachecount < HOSTCACHE_TOTALSIZE)
972 // Extract the IP addresses
976 if (hostcache_consoleoutput)
977 Con_Print("received server list...\n");
978 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
982 snprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
983 if (developer.integer)
984 Con_Printf("Requesting info from server %s\n", ipstring);
985 // ignore the rest of the message if the hostcache is full
986 if( hostcache_cachecount == HOSTCACHE_TOTALSIZE )
989 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
990 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
992 memset(&hostcache_cache[hostcache_cachecount], 0, sizeof(hostcache_cache[hostcache_cachecount]));
993 // store the data the engine cares about (address and ping)
994 strlcpy (hostcache_cache[hostcache_cachecount].info.cname, ipstring, sizeof (hostcache_cache[hostcache_cachecount].info.cname));
995 hostcache_cache[hostcache_cachecount].info.ping = 100000;
996 hostcache_cache[hostcache_cachecount].querytime = realtime;
997 // if not in the slist menu we should print the server to console
998 if (hostcache_consoleoutput)
999 Con_Printf("querying %s\n", ipstring);
1001 ++hostcache_cachecount;
1003 // move on to next address in packet
1010 if (!strncmp(string, "ping", 4))
1012 if (developer.integer)
1013 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1014 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1017 if (!strncmp(string, "ack", 3))
1020 // we may not have liked the packet, but it was a command packet, so
1021 // we're done processing this packet now
1024 // netquake control packets, supported for compatibility only
1025 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1030 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1034 if (developer.integer)
1035 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1036 if (cls.connect_trying)
1038 lhnetaddress_t clientportaddress;
1039 clientportaddress = *peeraddress;
1042 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1045 LHNETADDRESS_SetPort(&clientportaddress, port);
1047 M_Update_Return_Reason("Accepted");
1048 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1052 if (developer.integer)
1053 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1054 cls.connect_trying = false;
1055 M_Update_Return_Reason(data);
1058 case CCREP_SERVER_INFO:
1059 if (developer.integer)
1060 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1061 if (cls.state != ca_dedicated)
1063 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1064 // string we just ignore it and keep the real address
1066 // hostcache only uses text addresses
1067 cname = UDP_AddrToString(readaddr);
1068 // search the cache for this server
1069 for (n = 0; n < hostCacheCount; n++)
1070 if (!strcmp(cname, hostcache[n].cname))
1073 if (n == hostCacheCount && hostCacheCount < HOSTCACHESIZE)
1076 memset(&hostcache[n], 0, sizeof(hostcache[n]));
1077 strlcpy (hostcache[n].name, MSG_ReadString(), sizeof (hostcache[n].name));
1078 strlcpy (hostcache[n].map, MSG_ReadString(), sizeof (hostcache[n].map));
1079 hostcache[n].users = MSG_ReadByte();
1080 hostcache[n].maxusers = MSG_ReadByte();
1082 if (c != NET_PROTOCOL_VERSION)
1084 strlcpy (hostcache[n].cname, hostcache[n].name, sizeof (hostcache[n].cname));
1085 strcpy(hostcache[n].name, "*");
1086 strlcat (hostcache[n].name, hostcache[n].cname, sizeof(hostcache[n].name));
1088 strlcpy (hostcache[n].cname, cname, sizeof (hostcache[n].cname));
1092 case CCREP_PLAYER_INFO:
1093 // we got a CCREP_PLAYER_INFO??
1094 //if (developer.integer)
1095 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1097 case CCREP_RULE_INFO:
1098 // we got a CCREP_RULE_INFO??
1099 //if (developer.integer)
1100 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1106 // we may not have liked the packet, but it was a valid control
1107 // packet, so we're done processing this packet now
1111 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)
1112 CL_ParseServerMessage();
1116 void NetConn_ClientFrame(void)
1119 lhnetaddress_t peeraddress;
1121 NetConn_UpdateServerStuff();
1122 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1124 if (cls.connect_remainingtries == 0)
1126 cls.connect_trying = false;
1127 M_Update_Return_Reason("Connect: Failed");
1130 cls.connect_nextsendtime = realtime + 1;
1131 cls.connect_remainingtries--;
1132 // try challenge first (newer server)
1133 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1134 // then try netquake as a fallback (old server, or netquake)
1135 SZ_Clear(&net_message);
1136 // save space for the header, filled in later
1137 MSG_WriteLong(&net_message, 0);
1138 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1139 MSG_WriteString(&net_message, "QUAKE");
1140 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1141 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1142 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1143 SZ_Clear(&net_message);
1145 for (i = 0;i < cl_numsockets;i++)
1146 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1147 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1148 if (cls.netcon && realtime > cls.netcon->timeout)
1150 Con_Print("Connection timed out\n");
1152 Host_ShutdownServer (false);
1154 for (conn = netconn_list;conn;conn = conn->next)
1155 NetConn_ReSendMessage(conn);
1158 #define MAX_CHALLENGES 128
1161 lhnetaddress_t address;
1165 challenge[MAX_CHALLENGES];
1167 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1171 for (i = 0;i < bufferlength - 1;i++)
1175 c = rand () % (127 - 33) + 33;
1176 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1182 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1184 int i, n, ret, clientnum, responselength, best;
1188 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1192 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1194 // received a command string - strip off the packaging and put it
1195 // into our string buffer with NULL termination
1198 length = min(length, (int)sizeof(stringbuf) - 1);
1199 memcpy(stringbuf, data, length);
1200 stringbuf[length] = 0;
1203 if (developer.integer)
1205 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1206 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1207 Com_HexDumpToConsole(data, length);
1210 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1212 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1214 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1216 if (besttime > challenge[i].time)
1217 besttime = challenge[best = i].time;
1219 // if we did not find an exact match, choose the oldest and
1220 // update address and string
1221 if (i == MAX_CHALLENGES)
1224 challenge[i].address = *peeraddress;
1225 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1227 challenge[i].time = realtime;
1228 // send the challenge
1229 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1232 if (length > 8 && !memcmp(string, "connect\\", 8))
1236 if ((s = SearchInfostring(string, "challenge")))
1238 // validate the challenge
1239 for (i = 0;i < MAX_CHALLENGES;i++)
1240 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1242 if (i < MAX_CHALLENGES)
1244 // check engine protocol
1245 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1247 if (developer.integer)
1248 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1249 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1253 // see if this is a duplicate connection request
1254 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1255 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1257 if (clientnum < svs.maxclients)
1259 // duplicate connection request
1260 if (realtime - client->connecttime < 2.0)
1262 // client is still trying to connect,
1263 // so we send a duplicate reply
1264 if (developer.integer)
1265 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1266 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1268 // only kick if old connection seems dead
1269 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1271 // kick off connection and await retry
1272 client->deadsocket = true;
1277 // this is a new client, find a slot
1278 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1279 if (!client->active)
1281 if (clientnum < svs.maxclients)
1283 // prepare the client struct
1284 if ((conn = NetConn_Open(mysocket, peeraddress)))
1286 // allocated connection
1287 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1288 if (developer.integer)
1289 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1290 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1291 // now set up the client
1292 SV_ConnectClient(clientnum, conn);
1293 NetConn_Heartbeat(1);
1299 if (developer.integer)
1300 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1301 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1309 if (length >= 7 && !memcmp(string, "getinfo", 7))
1311 const char *challenge = NULL;
1312 // If there was a challenge in the getinfo message
1313 if (length > 8 && string[7] == ' ')
1314 challenge = string + 8;
1315 for (i = 0, n = 0;i < svs.maxclients;i++)
1316 if (svs.clients[i].active)
1318 responselength = snprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1319 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1320 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1321 gamename, com_modname, svs.maxclients, n,
1322 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1323 // does it fit in the buffer?
1324 if (responselength < (int)sizeof(response))
1326 if (developer.integer)
1327 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1328 NetConn_WriteString(mysocket, response, peeraddress);
1333 if (!strncmp(string, "ping", 4))
1335 if (developer.integer)
1336 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1337 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1340 if (!strncmp(string, "ack", 3))
1343 // we may not have liked the packet, but it was a command packet, so
1344 // we're done processing this packet now
1347 // LordHavoc: disabled netquake control packet support in server
1351 // netquake control packets, supported for compatibility only
1352 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1357 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1361 //if (developer.integer)
1362 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1363 if (length >= (int)strlen("QUAKE") + 1 + 1)
1365 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1367 if (developer.integer)
1368 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1369 SZ_Clear(&net_message);
1370 // save space for the header, filled in later
1371 MSG_WriteLong(&net_message, 0);
1372 MSG_WriteByte(&net_message, CCREP_REJECT);
1373 MSG_WriteString(&net_message, "Incompatible version.\n");
1374 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1375 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1376 SZ_Clear(&net_message);
1380 // see if this is a duplicate connection request
1381 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1382 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1384 if (clientnum < svs.maxclients)
1386 // duplicate connection request
1387 if (realtime - client->connecttime < 2.0)
1389 // client is still trying to connect,
1390 // so we send a duplicate reply
1391 if (developer.integer)
1392 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1393 SZ_Clear(&net_message);
1394 // save space for the header, filled in later
1395 MSG_WriteLong(&net_message, 0);
1396 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1397 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1398 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1399 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1400 SZ_Clear(&net_message);
1402 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1404 // the old client hasn't sent us anything
1405 // in quite a while, so kick off and let
1406 // the retry take care of it...
1407 client->deadsocket = true;
1412 // this is a new client, find a slot
1413 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1414 if (!client->active)
1416 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1418 // connect to the client
1419 // everything is allocated, just fill in the details
1420 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1421 if (developer.integer)
1422 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1423 // send back the info about the server connection
1424 SZ_Clear(&net_message);
1425 // save space for the header, filled in later
1426 MSG_WriteLong(&net_message, 0);
1427 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1428 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1429 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1430 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1431 SZ_Clear(&net_message);
1432 // now set up the client struct
1433 SV_ConnectClient(clientnum, conn);
1434 NetConn_Heartbeat(1);
1438 //if (developer.integer)
1439 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1440 // no room; try to let player know
1441 SZ_Clear(&net_message);
1442 // save space for the header, filled in later
1443 MSG_WriteLong(&net_message, 0);
1444 MSG_WriteByte(&net_message, CCREP_REJECT);
1445 MSG_WriteString(&net_message, "Server is full.\n");
1446 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1447 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1448 SZ_Clear(&net_message);
1455 case CCREQ_SERVER_INFO:
1456 if (developer.integer)
1457 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1458 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1460 if (developer.integer)
1461 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1462 SZ_Clear(&net_message);
1463 // save space for the header, filled in later
1464 MSG_WriteLong(&net_message, 0);
1465 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1466 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1467 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1468 MSG_WriteString(&net_message, hostname.string);
1469 MSG_WriteString(&net_message, sv.name);
1470 MSG_WriteByte(&net_message, net_activeconnections);
1471 MSG_WriteByte(&net_message, svs.maxclients);
1472 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1473 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1474 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1475 SZ_Clear(&net_message);
1478 case CCREQ_PLAYER_INFO:
1479 if (developer.integer)
1480 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1483 int playerNumber, activeNumber, clientNumber;
1486 playerNumber = MSG_ReadByte();
1488 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1489 if (client->active && ++activeNumber == playerNumber)
1491 if (clientNumber != svs.maxclients)
1493 SZ_Clear(&net_message);
1494 // save space for the header, filled in later
1495 MSG_WriteLong(&net_message, 0);
1496 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1497 MSG_WriteByte(&net_message, playerNumber);
1498 MSG_WriteString(&net_message, client->name);
1499 MSG_WriteLong(&net_message, client->colors);
1500 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1501 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1502 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1503 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1504 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1505 SZ_Clear(&net_message);
1509 case CCREQ_RULE_INFO:
1510 if (developer.integer)
1511 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1517 // find the search start location
1518 prevCvarName = MSG_ReadString();
1519 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1521 // send the response
1522 SZ_Clear(&net_message);
1523 // save space for the header, filled in later
1524 MSG_WriteLong(&net_message, 0);
1525 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1528 MSG_WriteString(&net_message, var->name);
1529 MSG_WriteString(&net_message, var->string);
1531 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1532 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1533 SZ_Clear(&net_message);
1540 // we may not have liked the packet, but it was a valid control
1541 // packet, so we're done processing this packet now
1546 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1548 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1550 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1551 SV_ReadClientMessage();
1559 void NetConn_ServerFrame(void)
1562 lhnetaddress_t peeraddress;
1564 NetConn_UpdateServerStuff();
1565 for (i = 0;i < sv_numsockets;i++)
1566 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1567 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1568 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1570 // never timeout loopback connections
1571 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1573 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1574 SV_DropClient(false);
1577 for (conn = netconn_list;conn;conn = conn->next)
1578 NetConn_ReSendMessage(conn);
1581 void NetConn_QueryMasters(void)
1585 lhnetaddress_t masteraddress;
1588 if (hostcache_cachecount >= HOSTCACHE_TOTALSIZE)
1591 for (i = 0;i < cl_numsockets;i++)
1598 UDP_Broadcast(UDP_controlSock, "\377\377\377\377getinfo", 11);
1600 SZ_Clear(&net_message);
1601 // save space for the header, filled in later
1602 MSG_WriteLong(&net_message, 0);
1603 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1604 MSG_WriteString(&net_message, "QUAKE");
1605 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1606 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1607 UDP_Broadcast(UDP_controlSock, net_message.data, net_message.cursize);
1608 SZ_Clear(&net_message);
1612 // build the getservers
1613 snprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1616 for (masternum = 0;sv_masters[masternum].name;masternum++)
1618 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1621 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1626 if (!masterquerycount)
1628 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1629 M_Update_Return_Reason("No network");
1633 void NetConn_Heartbeat(int priority)
1635 lhnetaddress_t masteraddress;
1637 lhnetsocket_t *mysocket;
1639 // if it's a state change (client connected), limit next heartbeat to no
1640 // more than 30 sec in the future
1641 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1642 nextheartbeattime = realtime + 30.0;
1644 // limit heartbeatperiod to 30 to 270 second range,
1645 // lower limit is to avoid abusing master servers with excess traffic,
1646 // upper limit is to avoid timing out on the master server (which uses
1648 if (sv_heartbeatperiod.value < 30)
1649 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1650 if (sv_heartbeatperiod.value > 270)
1651 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1653 // make advertising optional and don't advertise singleplayer games, and
1654 // only send a heartbeat as often as the admin wants
1655 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1657 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1658 for (masternum = 0;sv_masters[masternum].name;masternum++)
1659 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1660 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1664 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1667 qbyte sent[MAX_SCOREBOARD];
1669 memset(sent, 0, sizeof(sent));
1671 // simultaneously wait for the first CanSendMessage and send the message,
1672 // then wait for a second CanSendMessage (verifying it was received), or
1673 // the client drops and is no longer counted
1674 // the loop aborts when either it runs out of clients to send to, or a
1676 blocktime += Sys_DoubleTime();
1680 NetConn_ClientFrame();
1681 NetConn_ServerFrame();
1682 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1684 if (host_client->netconnection)
1686 if (NetConn_CanSendMessage(host_client->netconnection))
1689 NetConn_SendReliableMessage(host_client->netconnection, data);
1692 if (!NetConn_CanSendMessage(host_client->netconnection))
1697 while (count && Sys_DoubleTime() < blocktime);
1701 static void Net_Heartbeat_f(void)
1704 NetConn_Heartbeat(2);
1706 Con_Print("No server running, can not heartbeat to master server.\n");
1709 void PrintStats(netconn_t *conn)
1711 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1714 void Net_Stats_f(void)
1717 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1718 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1719 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1720 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1721 Con_Printf("packetsSent = %i\n", packetsSent);
1722 Con_Printf("packetsReSent = %i\n", packetsReSent);
1723 Con_Printf("packetsReceived = %i\n", packetsReceived);
1724 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1725 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1726 Con_Print("connections =\n");
1727 for (conn = netconn_list;conn;conn = conn->next)
1731 void Net_Slist_f(void)
1733 HostCache_ResetMasks();
1734 hostcache_sortbyfield = HCIF_PING;
1735 hostcache_sortdescending = false;
1736 if (m_state != m_slist) {
1737 Con_Print("Sending requests to master servers\n");
1738 HostCache_QueryList();
1739 hostcache_consoleoutput = true;
1740 Con_Print("Listening for replies...\n");
1742 HostCache_QueryList();
1744 //_HostCache_PingTest();
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();