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", "1"};
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", "ghdigital.com"}, //69.59.212.88
39 {0, "sv_masterextra2", "dpmaster.deathmask.net"}, //209.164.24.243
40 {0, "sv_masterextra3", "blaze.mindphukd.org"}, //12.166.196.192
44 static double nextheartbeattime = 0;
46 sizebuf_t net_message;
47 static qbyte net_message_buf[NET_MAXMESSAGE];
49 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
50 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
51 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
52 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
53 cvar_t developer_networking = {0, "developer_networking", "0"};
55 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
56 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
59 /* statistic counters */
60 static int packetsSent = 0;
61 static int packetsReSent = 0;
62 static int packetsReceived = 0;
63 static int receivedDuplicateCount = 0;
64 static int droppedDatagrams = 0;
66 static int unreliableMessagesSent = 0;
67 static int unreliableMessagesReceived = 0;
68 static int reliableMessagesSent = 0;
69 static int reliableMessagesReceived = 0;
71 double masterquerytime = -1000;
72 int masterquerycount = 0;
73 int masterreplycount = 0;
74 int serverquerycount = 0;
75 int serverreplycount = 0;
77 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
78 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
81 lhnetsocket_t *cl_sockets[16];
83 lhnetsocket_t *sv_sockets[16];
85 netconn_t *netconn_list = NULL;
86 mempool_t *netconn_mempool = NULL;
88 cvar_t cl_netport = {0, "cl_port", "0"};
89 cvar_t sv_netport = {0, "port", "26000"};
90 cvar_t net_address = {0, "net_address", "0.0.0.0"};
91 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
93 // ServerList interface
94 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
95 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
97 serverlist_infofield_t serverlist_sortbyfield;
98 qboolean serverlist_sortdescending;
100 int serverlist_viewcount = 0;
101 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
103 int serverlist_cachecount;
104 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
106 qboolean serverlist_consoleoutput;
108 // helper function to insert a value into the viewset
109 // spare entries will be removed
110 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
113 if( serverlist_viewcount == SERVERLIST_VIEWLISTSIZE )
116 for( i = serverlist_viewcount ; i > index ; i-- )
117 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
119 serverlist_viewlist[index] = entry;
120 serverlist_viewcount++;
123 // we suppose serverlist_viewcount to be valid, ie > 0
124 static void _ServerList_ViewList_Helper_Remove( int index )
126 serverlist_viewcount--;
127 for( ; index < serverlist_viewcount ; index++ )
128 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
131 // returns true if A should be inserted before B
132 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
134 int result = 0; // > 0 if for numbers A > B and for text if A < B
136 switch( serverlist_sortbyfield ) {
138 result = A->info.ping - B->info.ping;
140 case SLIF_MAXPLAYERS:
141 result = A->info.maxplayers - B->info.maxplayers;
143 case SLIF_NUMPLAYERS:
144 result = A->info.numplayers - B->info.numplayers;
147 result = A->info.protocol - B->info.protocol;
150 result = strcmp( B->info.cname, A->info.cname );
153 result = strcmp( B->info.game, A->info.game );
156 result = strcmp( B->info.map, A->info.map );
159 result = strcmp( B->info.mod, A->info.mod );
162 result = strcmp( B->info.name, A->info.name );
165 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
169 if( serverlist_sortdescending )
174 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
176 // This should actually be done with some intermediate and end-of-function return
188 case SLMO_GREATEREQUAL:
190 case SLMO_NOTCONTAIN:
193 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
198 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
200 // Same here, also using an intermediate & final return would be more appropriate
204 return *B && !!strstr( A, B ); // we want a real bool
205 case SLMO_NOTCONTAIN:
206 return !*B || !strstr( A, B );
208 return strcmp( A, B ) < 0;
210 return strcmp( A, B ) <= 0;
212 return strcmp( A, B ) == 0;
214 return strcmp( A, B ) > 0;
216 return strcmp( A, B ) != 0;
217 case SLMO_GREATEREQUAL:
218 return strcmp( A, B ) >= 0;
220 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
225 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
227 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
229 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
231 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
233 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
235 if( *mask->info.cname
236 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
239 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
242 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
245 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
248 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
253 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
257 if( serverlist_viewcount == SERVERLIST_VIEWLISTSIZE )
260 // now check whether it passes through the masks
261 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
262 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
265 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
266 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
268 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
271 if( !serverlist_viewcount ) {
272 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
275 // ok, insert it, we just need to find out where exactly:
278 // check whether to insert it as new first item
279 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
280 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
282 } // check whether to insert it as new last item
283 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
284 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
288 end = serverlist_viewcount - 1;
289 while( end > start + 1 )
291 mid = (start + end) / 2;
292 // test the item that lies in the middle between start and end
293 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
294 // the item has to be in the upper half
297 // the item has to be in the lower half
300 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
303 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
306 for( i = 0; i < serverlist_viewcount; i++ )
308 if (serverlist_viewlist[i] == entry)
310 _ServerList_ViewList_Helper_Remove(i);
316 void ServerList_RebuildViewList(void)
320 serverlist_viewcount = 0;
321 for( i = 0 ; i < serverlist_cachecount ; i++ )
322 if( serverlist_cache[i].finished )
323 ServerList_ViewList_Insert( &serverlist_cache[i] );
326 void ServerList_ResetMasks(void)
328 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
329 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
333 static void _ServerList_Test(void)
336 for( i = 0 ; i < 1024 ; i++ ) {
337 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
338 serverlist_cache[serverlist_cachecount].info.ping = rand() % 450 + 250;
339 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, 128, "Black's ServerList Test %i", i );
340 serverlist_cache[serverlist_cachecount].finished = true;
341 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
342 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
343 serverlist_cachecount++;
348 void ServerList_QueryList(void)
350 masterquerytime = realtime;
351 masterquerycount = 0;
352 masterreplycount = 0;
353 serverquerycount = 0;
354 serverreplycount = 0;
355 serverlist_cachecount = 0;
356 serverlist_viewcount = 0;
357 serverlist_consoleoutput = false;
358 NetConn_QueryMasters();
360 //_ServerList_Test();
365 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
367 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
371 if (cl_netpacketloss.integer)
372 for (i = 0;i < cl_numsockets;i++)
373 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
375 if (developer_networking.integer)
377 char addressstring[128], addressstring2[128];
378 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
381 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
382 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
383 Com_HexDumpToConsole(data, length);
386 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
391 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
395 if (cl_netpacketloss.integer)
396 for (i = 0;i < cl_numsockets;i++)
397 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
399 ret = LHNET_Write(mysocket, data, length, peeraddress);
400 if (developer_networking.integer)
402 char addressstring[128], addressstring2[128];
403 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
404 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
405 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
406 Com_HexDumpToConsole(data, length);
411 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
413 // note this does not include the trailing NULL because we add that in the parser
414 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
417 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
419 unsigned int packetLen;
420 unsigned int dataLen;
422 unsigned int *header;
425 if (data->cursize == 0)
426 Sys_Error("Datagram_SendMessage: zero length message\n");
428 if (data->cursize > (int)sizeof(conn->sendMessage))
429 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
431 if (conn->canSend == false)
432 Sys_Error("SendMessage: called with canSend == false\n");
435 memcpy(conn->sendMessage, data->data, data->cursize);
436 conn->sendMessageLength = data->cursize;
438 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
440 dataLen = conn->sendMessageLength;
445 dataLen = MAX_PACKETFRAGMENT;
449 packetLen = NET_HEADERSIZE + dataLen;
451 header = (void *)sendbuffer;
452 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
453 header[1] = BigLong(conn->sendSequence);
454 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
456 conn->sendSequence++;
457 conn->canSend = false;
459 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
462 conn->lastSendTime = realtime;
464 reliableMessagesSent++;
468 static void NetConn_SendMessageNext(netconn_t *conn)
470 unsigned int packetLen;
471 unsigned int dataLen;
473 unsigned int *header;
475 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
477 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
479 dataLen = conn->sendMessageLength;
484 dataLen = MAX_PACKETFRAGMENT;
488 packetLen = NET_HEADERSIZE + dataLen;
490 header = (void *)sendbuffer;
491 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
492 header[1] = BigLong(conn->sendSequence);
493 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
495 conn->sendSequence++;
496 conn->sendNext = false;
498 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
501 conn->lastSendTime = realtime;
506 static void NetConn_ReSendMessage(netconn_t *conn)
508 unsigned int packetLen;
509 unsigned int dataLen;
511 unsigned int *header;
513 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
515 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
517 dataLen = conn->sendMessageLength;
522 dataLen = MAX_PACKETFRAGMENT;
526 packetLen = NET_HEADERSIZE + dataLen;
528 header = (void *)sendbuffer;
529 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
530 header[1] = BigLong(conn->sendSequence - 1);
531 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
533 conn->sendNext = false;
535 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
538 conn->lastSendTime = realtime;
543 qboolean NetConn_CanSendMessage(netconn_t *conn)
545 return conn->canSend;
548 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
553 packetLen = NET_HEADERSIZE + data->cursize;
556 if (data->cursize == 0)
557 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
559 if (packetLen > (int)sizeof(sendbuffer))
560 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
563 header = (void *)sendbuffer;
564 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
565 header[1] = BigLong(conn->unreliableSendSequence);
566 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
568 conn->unreliableSendSequence++;
570 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
574 unreliableMessagesSent++;
578 void NetConn_CloseClientPorts(void)
580 for (;cl_numsockets > 0;cl_numsockets--)
581 if (cl_sockets[cl_numsockets - 1])
582 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
585 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
587 lhnetaddress_t address;
589 char addressstring2[1024];
590 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
592 if ((s = LHNET_OpenSocket_Connectionless(&address)))
594 cl_sockets[cl_numsockets++] = s;
595 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
596 Con_Printf("Client opened a socket on address %s\n", addressstring2);
600 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
601 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
605 Con_Printf("Client unable to parse address %s\n", addressstring);
608 void NetConn_OpenClientPorts(void)
611 NetConn_CloseClientPorts();
612 port = bound(0, cl_netport.integer, 65535);
613 if (cl_netport.integer != port)
614 Cvar_SetValueQuick(&cl_netport, port);
615 Con_Printf("Client using port %i\n", port);
616 NetConn_OpenClientPort("local:2", 0);
617 NetConn_OpenClientPort(net_address.string, port);
618 //NetConn_OpenClientPort(net_address_ipv6.string, port);
621 void NetConn_CloseServerPorts(void)
623 for (;sv_numsockets > 0;sv_numsockets--)
624 if (sv_sockets[sv_numsockets - 1])
625 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
628 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
630 lhnetaddress_t address;
632 char addressstring2[1024];
633 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
635 if ((s = LHNET_OpenSocket_Connectionless(&address)))
637 sv_sockets[sv_numsockets++] = s;
638 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
639 Con_Printf("Server listening on address %s\n", addressstring2);
643 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
644 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
648 Con_Printf("Server unable to parse address %s\n", addressstring);
651 void NetConn_OpenServerPorts(int opennetports)
654 NetConn_CloseServerPorts();
655 port = bound(0, sv_netport.integer, 65535);
658 Con_Printf("Server using port %i\n", port);
659 if (sv_netport.integer != port)
660 Cvar_SetValueQuick(&sv_netport, port);
661 if (cls.state != ca_dedicated)
662 NetConn_OpenServerPort("local:1", 0);
665 NetConn_OpenServerPort(net_address.string, port);
666 //NetConn_OpenServerPort(net_address_ipv6.string, port);
668 if (sv_numsockets == 0)
669 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
672 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
674 int i, a = LHNETADDRESS_GetAddressType(address);
675 for (i = 0;i < cl_numsockets;i++)
676 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
677 return cl_sockets[i];
681 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
683 int i, a = LHNETADDRESS_GetAddressType(address);
684 for (i = 0;i < sv_numsockets;i++)
685 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
686 return sv_sockets[i];
690 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
693 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
694 conn->mysocket = mysocket;
695 conn->peeraddress = *peeraddress;
696 conn->canSend = true;
697 conn->lastMessageTime = realtime;
698 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
699 // reduce effectiveness of connection request floods
700 conn->timeout = realtime + net_connecttimeout.value;
701 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
702 conn->next = netconn_list;
707 void NetConn_Close(netconn_t *conn)
710 // remove connection from list
711 if (conn == netconn_list)
712 netconn_list = conn->next;
715 for (c = netconn_list;c;c = c->next)
719 c->next = conn->next;
723 // not found in list, we'll avoid crashing here...
731 static int clientport = -1;
732 static int clientport2 = -1;
733 static int hostport = -1;
734 static void NetConn_UpdateServerStuff(void)
736 if (cls.state != ca_dedicated)
738 if (clientport2 != cl_netport.integer)
740 clientport2 = cl_netport.integer;
741 if (cls.state == ca_connected)
742 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
744 if (cls.state == ca_disconnected && clientport != clientport2)
746 clientport = clientport2;
747 NetConn_CloseClientPorts();
749 if (cl_numsockets == 0)
750 NetConn_OpenClientPorts();
753 if (hostport != sv_netport.integer)
755 hostport = sv_netport.integer;
757 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
761 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
765 unsigned int sequence;
769 length = BigLong(((int *)data)[0]);
770 flags = length & ~NETFLAG_LENGTH_MASK;
771 length &= NETFLAG_LENGTH_MASK;
772 // control packets were already handled
773 if (!(flags & NETFLAG_CTL))
775 sequence = BigLong(((int *)data)[1]);
779 if (flags & NETFLAG_UNRELIABLE)
781 if (sequence >= conn->unreliableReceiveSequence)
783 if (sequence > conn->unreliableReceiveSequence)
785 count = sequence - conn->unreliableReceiveSequence;
786 droppedDatagrams += count;
787 Con_DPrintf("Dropped %u datagram(s)\n", count);
789 conn->unreliableReceiveSequence = sequence + 1;
790 conn->lastMessageTime = realtime;
791 conn->timeout = realtime + net_messagetimeout.value;
792 unreliableMessagesReceived++;
795 SZ_Clear(&net_message);
796 SZ_Write(&net_message, data, length);
802 Con_DPrint("Got a stale datagram\n");
805 else if (flags & NETFLAG_ACK)
807 if (sequence == (conn->sendSequence - 1))
809 if (sequence == conn->ackSequence)
812 if (conn->ackSequence != conn->sendSequence)
813 Con_DPrint("ack sequencing error\n");
814 conn->lastMessageTime = realtime;
815 conn->timeout = realtime + net_messagetimeout.value;
816 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
817 if (conn->sendMessageLength > 0)
819 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
820 conn->sendNext = true;
821 NetConn_SendMessageNext(conn);
825 conn->sendMessageLength = 0;
826 conn->canSend = true;
830 Con_DPrint("Duplicate ACK received\n");
833 Con_DPrint("Stale ACK received\n");
836 else if (flags & NETFLAG_DATA)
838 unsigned int temppacket[2];
839 temppacket[0] = BigLong(8 | NETFLAG_ACK);
840 temppacket[1] = BigLong(sequence);
841 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
842 if (sequence == conn->receiveSequence)
844 conn->lastMessageTime = realtime;
845 conn->timeout = realtime + net_messagetimeout.value;
846 conn->receiveSequence++;
847 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
848 conn->receiveMessageLength += length;
849 if (flags & NETFLAG_EOM)
851 reliableMessagesReceived++;
852 length = conn->receiveMessageLength;
853 conn->receiveMessageLength = 0;
856 SZ_Clear(&net_message);
857 SZ_Write(&net_message, conn->receiveMessage, length);
864 receivedDuplicateCount++;
872 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
874 cls.connect_trying = false;
875 M_Update_Return_Reason("");
876 // the connection request succeeded, stop current connection and set up a new connection
878 cls.netcon = NetConn_Open(mysocket, peeraddress);
879 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
882 cls.demonum = -1; // not in the demo loop now
883 cls.state = ca_connected;
884 cls.signon = 0; // need all the signon messages before playing
887 int NetConn_IsLocalGame(void)
889 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
894 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
897 lhnetaddress_t svaddress;
899 char *string, addressstring2[128], cname[128], ipstring[32];
900 char stringbuf[16384];
902 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
904 // received a command string - strip off the packaging and put it
905 // into our string buffer with NULL termination
908 length = min(length, (int)sizeof(stringbuf) - 1);
909 memcpy(stringbuf, data, length);
910 stringbuf[length] = 0;
913 if (developer.integer)
915 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
916 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
917 Com_HexDumpToConsole(data, length);
920 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
922 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
923 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
924 M_Update_Return_Reason("Got challenge response");
925 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
928 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
930 M_Update_Return_Reason("Accepted");
931 NetConn_ConnectionEstablished(mysocket, peeraddress);
934 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
936 char rejectreason[32];
937 cls.connect_trying = false;
939 length = max(length - 7, (int)sizeof(rejectreason) - 1);
940 memcpy(rejectreason, string, length);
941 rejectreason[length] = 0;
942 M_Update_Return_Reason(rejectreason);
945 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
947 serverlist_info_t *info;
952 // serverlist only uses text addresses
953 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
954 // search the cache for this server and update it
955 for( n = 0; n < serverlist_cachecount; n++ )
956 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
958 if( n == serverlist_cachecount )
961 info = &serverlist_cache[n].info;
962 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
963 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
964 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
965 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
966 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
967 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
968 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
970 if (info->ping == 100000)
973 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
974 pingtime = bound(0, pingtime, 9999);
976 info->ping = pingtime;
978 // legacy/old stuff move it to the menu ASAP
980 // build description strings for the things users care about
981 dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "%5d%c%3u/%3u %-65.65s", (int)pingtime, info->protocol != NET_PROTOCOL_VERSION ? '*' : ' ', info->numplayers, info->maxplayers, info->name);
982 dpsnprintf(serverlist_cache[n].line2, sizeof(serverlist_cache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", info->cname, info->game, info->mod, info->map);
983 // if ping is especially high, display it as such
986 // orange numbers (lower block)
987 for (i = 0;i < 5;i++)
988 if (serverlist_cache[n].line1[i] != ' ')
989 serverlist_cache[n].line1[i] += 128;
991 else if (pingtime >= 200)
993 // yellow numbers (in upper block)
994 for (i = 0;i < 5;i++)
995 if (serverlist_cache[n].line1[i] != ' ')
996 serverlist_cache[n].line1[i] -= 30;
998 // and finally, update the view set
999 if( serverlist_cache[n].finished )
1000 ServerList_ViewList_Remove( &serverlist_cache[n] );
1001 // else if not in the slist menu we should print the server to console (if wanted)
1002 else if( serverlist_consoleoutput )
1003 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1004 ServerList_ViewList_Insert( &serverlist_cache[n] );
1005 serverlist_cache[n].finished = true;
1009 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1011 // Extract the IP addresses
1015 if (serverlist_consoleoutput)
1016 Con_Print("received server list...\n");
1017 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1021 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1022 if (developer.integer)
1023 Con_Printf("Requesting info from server %s\n", ipstring);
1024 // ignore the rest of the message if the serverlist is full
1025 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1027 // also ignore it if we have already queried it (other master server response)
1028 for( n = 0 ; n < serverlist_cachecount ; n++ )
1029 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1031 if( n >= serverlist_cachecount )
1035 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
1036 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
1038 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1039 // store the data the engine cares about (address and ping)
1040 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1041 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1042 serverlist_cache[serverlist_cachecount].querytime = realtime;
1043 // if not in the slist menu we should print the server to console
1044 if (serverlist_consoleoutput)
1045 Con_Printf("querying %s\n", ipstring);
1047 ++serverlist_cachecount;
1050 // move on to next address in packet
1057 if (!strncmp(string, "ping", 4))
1059 if (developer.integer)
1060 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1061 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1064 if (!strncmp(string, "ack", 3))
1067 // we may not have liked the packet, but it was a command packet, so
1068 // we're done processing this packet now
1071 // netquake control packets, supported for compatibility only
1072 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1077 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1081 if (developer.integer)
1082 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1083 if (cls.connect_trying)
1085 lhnetaddress_t clientportaddress;
1086 clientportaddress = *peeraddress;
1089 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1092 LHNETADDRESS_SetPort(&clientportaddress, port);
1094 M_Update_Return_Reason("Accepted");
1095 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1099 if (developer.integer)
1100 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1101 cls.connect_trying = false;
1102 M_Update_Return_Reason(data);
1105 case CCREP_SERVER_INFO:
1106 if (developer.integer)
1107 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1108 if (cls.state != ca_dedicated)
1110 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1111 // string we just ignore it and keep the real address
1113 // serverlist only uses text addresses
1114 cname = UDP_AddrToString(readaddr);
1115 // search the cache for this server
1116 for (n = 0; n < hostCacheCount; n++)
1117 if (!strcmp(cname, serverlist[n].cname))
1120 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1123 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1124 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1125 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1126 serverlist[n].users = MSG_ReadByte();
1127 serverlist[n].maxusers = MSG_ReadByte();
1129 if (c != NET_PROTOCOL_VERSION)
1131 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1132 strcpy(serverlist[n].name, "*");
1133 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1135 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1139 case CCREP_PLAYER_INFO:
1140 // we got a CCREP_PLAYER_INFO??
1141 //if (developer.integer)
1142 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1144 case CCREP_RULE_INFO:
1145 // we got a CCREP_RULE_INFO??
1146 //if (developer.integer)
1147 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1153 // we may not have liked the packet, but it was a valid control
1154 // packet, so we're done processing this packet now
1158 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)
1159 CL_ParseServerMessage();
1163 void NetConn_ClientFrame(void)
1166 lhnetaddress_t peeraddress;
1168 NetConn_UpdateServerStuff();
1169 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1171 if (cls.connect_remainingtries == 0)
1172 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1173 cls.connect_nextsendtime = realtime + 1;
1174 cls.connect_remainingtries--;
1175 if (cls.connect_remainingtries <= -10)
1177 cls.connect_trying = false;
1178 M_Update_Return_Reason("Connect: Failed");
1181 // try challenge first (newer server)
1182 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1183 // then try netquake as a fallback (old server, or netquake)
1184 SZ_Clear(&net_message);
1185 // save space for the header, filled in later
1186 MSG_WriteLong(&net_message, 0);
1187 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1188 MSG_WriteString(&net_message, "QUAKE");
1189 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1190 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1191 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1192 SZ_Clear(&net_message);
1194 for (i = 0;i < cl_numsockets;i++)
1195 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1196 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1197 if (cls.netcon && realtime > cls.netcon->timeout)
1199 Con_Print("Connection timed out\n");
1201 Host_ShutdownServer (false);
1203 for (conn = netconn_list;conn;conn = conn->next)
1204 NetConn_ReSendMessage(conn);
1207 #define MAX_CHALLENGES 128
1210 lhnetaddress_t address;
1214 challenge[MAX_CHALLENGES];
1216 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1220 for (i = 0;i < bufferlength - 1;i++)
1224 c = rand () % (127 - 33) + 33;
1225 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1231 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1233 int i, n, ret, clientnum, responselength, best;
1237 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1241 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1243 // received a command string - strip off the packaging and put it
1244 // into our string buffer with NULL termination
1247 length = min(length, (int)sizeof(stringbuf) - 1);
1248 memcpy(stringbuf, data, length);
1249 stringbuf[length] = 0;
1252 if (developer.integer)
1254 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1255 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1256 Com_HexDumpToConsole(data, length);
1259 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1261 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1263 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1265 if (besttime > challenge[i].time)
1266 besttime = challenge[best = i].time;
1268 // if we did not find an exact match, choose the oldest and
1269 // update address and string
1270 if (i == MAX_CHALLENGES)
1273 challenge[i].address = *peeraddress;
1274 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1276 challenge[i].time = realtime;
1277 // send the challenge
1278 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1281 if (length > 8 && !memcmp(string, "connect\\", 8))
1285 if ((s = SearchInfostring(string, "challenge")))
1287 // validate the challenge
1288 for (i = 0;i < MAX_CHALLENGES;i++)
1289 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1291 if (i < MAX_CHALLENGES)
1293 // check engine protocol
1294 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1296 if (developer.integer)
1297 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1298 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1302 // see if this is a duplicate connection request
1303 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1304 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1306 if (clientnum < svs.maxclients)
1308 // duplicate connection request
1309 if (realtime - client->connecttime < 2.0)
1311 // client is still trying to connect,
1312 // so we send a duplicate reply
1313 if (developer.integer)
1314 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1315 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1317 // only kick if old connection seems dead
1318 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1320 // kick off connection and await retry
1321 client->deadsocket = true;
1326 // this is a new client, find a slot
1327 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1328 if (!client->active)
1330 if (clientnum < svs.maxclients)
1332 // prepare the client struct
1333 if ((conn = NetConn_Open(mysocket, peeraddress)))
1335 // allocated connection
1336 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1337 if (developer.integer)
1338 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1339 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1340 // now set up the client
1341 SV_ConnectClient(clientnum, conn);
1342 NetConn_Heartbeat(1);
1348 if (developer.integer)
1349 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1350 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1358 if (length >= 7 && !memcmp(string, "getinfo", 7))
1360 const char *challenge = NULL;
1361 // If there was a challenge in the getinfo message
1362 if (length > 8 && string[7] == ' ')
1363 challenge = string + 8;
1364 for (i = 0, n = 0;i < svs.maxclients;i++)
1365 if (svs.clients[i].active)
1367 responselength = dpsnprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1368 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1369 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1370 gamename, com_modname, svs.maxclients, n,
1371 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1372 // does it fit in the buffer?
1373 if (responselength >= 0)
1375 if (developer.integer)
1376 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1377 NetConn_WriteString(mysocket, response, peeraddress);
1382 if (!strncmp(string, "ping", 4))
1384 if (developer.integer)
1385 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1386 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1389 if (!strncmp(string, "ack", 3))
1392 // we may not have liked the packet, but it was a command packet, so
1393 // we're done processing this packet now
1396 // LordHavoc: disabled netquake control packet support in server
1400 // netquake control packets, supported for compatibility only
1401 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1406 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1410 //if (developer.integer)
1411 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1412 if (length >= (int)strlen("QUAKE") + 1 + 1)
1414 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1416 if (developer.integer)
1417 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1418 SZ_Clear(&net_message);
1419 // save space for the header, filled in later
1420 MSG_WriteLong(&net_message, 0);
1421 MSG_WriteByte(&net_message, CCREP_REJECT);
1422 MSG_WriteString(&net_message, "Incompatible version.\n");
1423 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1424 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1425 SZ_Clear(&net_message);
1429 // see if this is a duplicate connection request
1430 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1431 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1433 if (clientnum < svs.maxclients)
1435 // duplicate connection request
1436 if (realtime - client->connecttime < 2.0)
1438 // client is still trying to connect,
1439 // so we send a duplicate reply
1440 if (developer.integer)
1441 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1442 SZ_Clear(&net_message);
1443 // save space for the header, filled in later
1444 MSG_WriteLong(&net_message, 0);
1445 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1446 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1447 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1448 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1449 SZ_Clear(&net_message);
1451 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1453 // the old client hasn't sent us anything
1454 // in quite a while, so kick off and let
1455 // the retry take care of it...
1456 client->deadsocket = true;
1461 // this is a new client, find a slot
1462 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1463 if (!client->active)
1465 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1467 // connect to the client
1468 // everything is allocated, just fill in the details
1469 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1470 if (developer.integer)
1471 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1472 // send back the info about the server connection
1473 SZ_Clear(&net_message);
1474 // save space for the header, filled in later
1475 MSG_WriteLong(&net_message, 0);
1476 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1477 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1478 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1479 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1480 SZ_Clear(&net_message);
1481 // now set up the client struct
1482 SV_ConnectClient(clientnum, conn);
1483 NetConn_Heartbeat(1);
1487 //if (developer.integer)
1488 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1489 // no room; try to let player know
1490 SZ_Clear(&net_message);
1491 // save space for the header, filled in later
1492 MSG_WriteLong(&net_message, 0);
1493 MSG_WriteByte(&net_message, CCREP_REJECT);
1494 MSG_WriteString(&net_message, "Server is full.\n");
1495 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1496 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1497 SZ_Clear(&net_message);
1504 case CCREQ_SERVER_INFO:
1505 if (developer.integer)
1506 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1507 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1509 if (developer.integer)
1510 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1511 SZ_Clear(&net_message);
1512 // save space for the header, filled in later
1513 MSG_WriteLong(&net_message, 0);
1514 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1515 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1516 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1517 MSG_WriteString(&net_message, hostname.string);
1518 MSG_WriteString(&net_message, sv.name);
1519 MSG_WriteByte(&net_message, net_activeconnections);
1520 MSG_WriteByte(&net_message, svs.maxclients);
1521 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1522 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1523 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1524 SZ_Clear(&net_message);
1527 case CCREQ_PLAYER_INFO:
1528 if (developer.integer)
1529 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1532 int playerNumber, activeNumber, clientNumber;
1535 playerNumber = MSG_ReadByte();
1537 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1538 if (client->active && ++activeNumber == playerNumber)
1540 if (clientNumber != svs.maxclients)
1542 SZ_Clear(&net_message);
1543 // save space for the header, filled in later
1544 MSG_WriteLong(&net_message, 0);
1545 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1546 MSG_WriteByte(&net_message, playerNumber);
1547 MSG_WriteString(&net_message, client->name);
1548 MSG_WriteLong(&net_message, client->colors);
1549 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1550 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1551 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1552 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1553 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1554 SZ_Clear(&net_message);
1558 case CCREQ_RULE_INFO:
1559 if (developer.integer)
1560 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1566 // find the search start location
1567 prevCvarName = MSG_ReadString();
1568 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1570 // send the response
1571 SZ_Clear(&net_message);
1572 // save space for the header, filled in later
1573 MSG_WriteLong(&net_message, 0);
1574 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1577 MSG_WriteString(&net_message, var->name);
1578 MSG_WriteString(&net_message, var->string);
1580 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1581 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1582 SZ_Clear(&net_message);
1589 // we may not have liked the packet, but it was a valid control
1590 // packet, so we're done processing this packet now
1595 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1597 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1599 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1600 SV_ReadClientMessage();
1608 void NetConn_ServerFrame(void)
1611 lhnetaddress_t peeraddress;
1613 NetConn_UpdateServerStuff();
1614 for (i = 0;i < sv_numsockets;i++)
1615 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1616 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1617 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1619 // never timeout loopback connections
1620 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1622 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1623 SV_DropClient(false);
1626 for (conn = netconn_list;conn;conn = conn->next)
1627 NetConn_ReSendMessage(conn);
1630 void NetConn_QueryMasters(void)
1634 lhnetaddress_t masteraddress;
1635 lhnetaddress_t broadcastaddress;
1638 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1641 // 26000 is the default quake server port, servers on other ports will not
1643 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1644 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1646 for (i = 0;i < cl_numsockets;i++)
1650 // search LAN for Quake servers
1651 SZ_Clear(&net_message);
1652 // save space for the header, filled in later
1653 MSG_WriteLong(&net_message, 0);
1654 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1655 MSG_WriteString(&net_message, "QUAKE");
1656 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1657 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1658 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1659 SZ_Clear(&net_message);
1661 // search LAN for DarkPlaces servers
1662 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1664 // build the getservers message to send to the master servers
1665 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1668 for (masternum = 0;sv_masters[masternum].name;masternum++)
1670 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1673 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1678 if (!masterquerycount)
1680 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1681 M_Update_Return_Reason("No network");
1685 void NetConn_Heartbeat(int priority)
1687 lhnetaddress_t masteraddress;
1689 lhnetsocket_t *mysocket;
1691 // if it's a state change (client connected), limit next heartbeat to no
1692 // more than 30 sec in the future
1693 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1694 nextheartbeattime = realtime + 30.0;
1696 // limit heartbeatperiod to 30 to 270 second range,
1697 // lower limit is to avoid abusing master servers with excess traffic,
1698 // upper limit is to avoid timing out on the master server (which uses
1700 if (sv_heartbeatperiod.value < 30)
1701 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1702 if (sv_heartbeatperiod.value > 270)
1703 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1705 // make advertising optional and don't advertise singleplayer games, and
1706 // only send a heartbeat as often as the admin wants
1707 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1709 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1710 for (masternum = 0;sv_masters[masternum].name;masternum++)
1711 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1712 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1716 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1719 qbyte sent[MAX_SCOREBOARD];
1721 memset(sent, 0, sizeof(sent));
1723 // simultaneously wait for the first CanSendMessage and send the message,
1724 // then wait for a second CanSendMessage (verifying it was received), or
1725 // the client drops and is no longer counted
1726 // the loop aborts when either it runs out of clients to send to, or a
1728 blocktime += Sys_DoubleTime();
1732 NetConn_ClientFrame();
1733 NetConn_ServerFrame();
1734 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1736 if (host_client->netconnection)
1738 if (NetConn_CanSendMessage(host_client->netconnection))
1741 NetConn_SendReliableMessage(host_client->netconnection, data);
1744 if (!NetConn_CanSendMessage(host_client->netconnection))
1749 while (count && Sys_DoubleTime() < blocktime);
1753 static void Net_Heartbeat_f(void)
1756 NetConn_Heartbeat(2);
1758 Con_Print("No server running, can not heartbeat to master server.\n");
1761 void PrintStats(netconn_t *conn)
1763 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1766 void Net_Stats_f(void)
1769 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1770 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1771 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1772 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1773 Con_Printf("packetsSent = %i\n", packetsSent);
1774 Con_Printf("packetsReSent = %i\n", packetsReSent);
1775 Con_Printf("packetsReceived = %i\n", packetsReceived);
1776 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1777 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1778 Con_Print("connections =\n");
1779 for (conn = netconn_list;conn;conn = conn->next)
1783 void Net_Slist_f(void)
1785 ServerList_ResetMasks();
1786 serverlist_sortbyfield = SLIF_PING;
1787 serverlist_sortdescending = false;
1788 if (m_state != m_slist) {
1789 Con_Print("Sending requests to master servers\n");
1790 ServerList_QueryList();
1791 serverlist_consoleoutput = true;
1792 Con_Print("Listening for replies...\n");
1794 ServerList_QueryList();
1797 void NetConn_Init(void)
1800 lhnetaddress_t tempaddress;
1801 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
1802 Cmd_AddCommand("net_stats", Net_Stats_f);
1803 Cmd_AddCommand("net_slist", Net_Slist_f);
1804 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1805 Cvar_RegisterVariable(&net_messagetimeout);
1806 Cvar_RegisterVariable(&net_messagerejointimeout);
1807 Cvar_RegisterVariable(&net_connecttimeout);
1808 Cvar_RegisterVariable(&cl_netlocalping);
1809 Cvar_RegisterVariable(&cl_netpacketloss);
1810 Cvar_RegisterVariable(&hostname);
1811 Cvar_RegisterVariable(&developer_networking);
1812 Cvar_RegisterVariable(&cl_netport);
1813 Cvar_RegisterVariable(&sv_netport);
1814 Cvar_RegisterVariable(&net_address);
1815 //Cvar_RegisterVariable(&net_address_ipv6);
1816 Cvar_RegisterVariable(&sv_public);
1817 Cvar_RegisterVariable(&sv_heartbeatperiod);
1818 for (i = 0;sv_masters[i].name;i++)
1819 Cvar_RegisterVariable(&sv_masters[i]);
1820 // 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.
1821 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1823 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1825 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1826 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1829 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1831 // 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
1832 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1834 i = atoi(com_argv[i + 1]);
1835 if (i >= 0 && i < 65536)
1837 Con_Printf("-port option used, setting port cvar to %i\n", i);
1838 Cvar_SetValueQuick(&sv_netport, i);
1841 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1845 net_message.data = net_message_buf;
1846 net_message.maxsize = sizeof(net_message_buf);
1847 net_message.cursize = 0;
1851 void NetConn_Shutdown(void)
1853 NetConn_CloseClientPorts();
1854 NetConn_CloseServerPorts();