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", "120"};
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", "12.166.196.192"}, //blaze.mindphukd.org (doesn't resolve currently but works as an ip)
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 ) {
114 i = serverlist_viewcount++;
116 i = SERVERLIST_VIEWLISTSIZE - 1;
119 for( ; i > index ; i-- )
120 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
122 serverlist_viewlist[index] = entry;
125 // we suppose serverlist_viewcount to be valid, ie > 0
126 static void _ServerList_ViewList_Helper_Remove( int index )
128 serverlist_viewcount--;
129 for( ; index < serverlist_viewcount ; index++ )
130 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
133 // returns true if A should be inserted before B
134 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
136 int result = 0; // > 0 if for numbers A > B and for text if A < B
138 switch( serverlist_sortbyfield ) {
140 result = A->info.ping - B->info.ping;
142 case SLIF_MAXPLAYERS:
143 result = A->info.maxplayers - B->info.maxplayers;
145 case SLIF_NUMPLAYERS:
146 result = A->info.numplayers - B->info.numplayers;
149 result = A->info.protocol - B->info.protocol;
152 result = strcmp( B->info.cname, A->info.cname );
155 result = strcmp( B->info.game, A->info.game );
158 result = strcmp( B->info.map, A->info.map );
161 result = strcmp( B->info.mod, A->info.mod );
164 result = strcmp( B->info.name, A->info.name );
167 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
171 if( serverlist_sortdescending )
176 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
178 // This should actually be done with some intermediate and end-of-function return
190 case SLMO_GREATEREQUAL:
192 case SLMO_NOTCONTAIN:
195 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
200 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
202 // Same here, also using an intermediate & final return would be more appropriate
206 return *B && !!strstr( A, B ); // we want a real bool
207 case SLMO_NOTCONTAIN:
208 return !*B || !strstr( A, B );
210 return strcmp( A, B ) < 0;
212 return strcmp( A, B ) <= 0;
214 return strcmp( A, B ) == 0;
216 return strcmp( A, B ) > 0;
218 return strcmp( A, B ) != 0;
219 case SLMO_GREATEREQUAL:
220 return strcmp( A, B ) >= 0;
222 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
227 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
229 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
231 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
233 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
235 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
237 if( *mask->info.cname
238 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
241 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
244 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
247 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
250 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
255 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
259 // FIXME: change this to be more readable (...)
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 = 1000 + 1024 - i;
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;
359 //_ServerList_Test();
361 NetConn_QueryMasters();
366 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
368 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
372 if (cl_netpacketloss.integer)
373 for (i = 0;i < cl_numsockets;i++)
374 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
376 if (developer_networking.integer)
378 char addressstring[128], addressstring2[128];
379 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
382 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
383 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
384 Com_HexDumpToConsole(data, length);
387 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
392 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
396 if (cl_netpacketloss.integer)
397 for (i = 0;i < cl_numsockets;i++)
398 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
400 ret = LHNET_Write(mysocket, data, length, peeraddress);
401 if (developer_networking.integer)
403 char addressstring[128], addressstring2[128];
404 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
405 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
406 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
407 Com_HexDumpToConsole(data, length);
412 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
414 // note this does not include the trailing NULL because we add that in the parser
415 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
418 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
420 unsigned int packetLen;
421 unsigned int dataLen;
423 unsigned int *header;
426 if (data->cursize == 0)
427 Sys_Error("Datagram_SendMessage: zero length message\n");
429 if (data->cursize > (int)sizeof(conn->sendMessage))
430 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
432 if (conn->canSend == false)
433 Sys_Error("SendMessage: called with canSend == false\n");
436 memcpy(conn->sendMessage, data->data, data->cursize);
437 conn->sendMessageLength = data->cursize;
439 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
441 dataLen = conn->sendMessageLength;
446 dataLen = MAX_PACKETFRAGMENT;
450 packetLen = NET_HEADERSIZE + dataLen;
452 header = (void *)sendbuffer;
453 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
454 header[1] = BigLong(conn->sendSequence);
455 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
457 conn->sendSequence++;
458 conn->canSend = false;
460 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
463 conn->lastSendTime = realtime;
465 reliableMessagesSent++;
469 static void NetConn_SendMessageNext(netconn_t *conn)
471 unsigned int packetLen;
472 unsigned int dataLen;
474 unsigned int *header;
476 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
478 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
480 dataLen = conn->sendMessageLength;
485 dataLen = MAX_PACKETFRAGMENT;
489 packetLen = NET_HEADERSIZE + dataLen;
491 header = (void *)sendbuffer;
492 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
493 header[1] = BigLong(conn->sendSequence);
494 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
496 conn->sendSequence++;
497 conn->sendNext = false;
499 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
502 conn->lastSendTime = realtime;
507 static void NetConn_ReSendMessage(netconn_t *conn)
509 unsigned int packetLen;
510 unsigned int dataLen;
512 unsigned int *header;
514 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
516 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
518 dataLen = conn->sendMessageLength;
523 dataLen = MAX_PACKETFRAGMENT;
527 packetLen = NET_HEADERSIZE + dataLen;
529 header = (void *)sendbuffer;
530 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
531 header[1] = BigLong(conn->sendSequence - 1);
532 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
534 conn->sendNext = false;
536 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
539 conn->lastSendTime = realtime;
544 qboolean NetConn_CanSendMessage(netconn_t *conn)
546 return conn->canSend;
549 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
554 packetLen = NET_HEADERSIZE + data->cursize;
557 if (data->cursize == 0)
558 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
560 if (packetLen > (int)sizeof(sendbuffer))
561 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
564 header = (void *)sendbuffer;
565 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
566 header[1] = BigLong(conn->unreliableSendSequence);
567 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
569 conn->unreliableSendSequence++;
571 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
575 unreliableMessagesSent++;
579 void NetConn_CloseClientPorts(void)
581 for (;cl_numsockets > 0;cl_numsockets--)
582 if (cl_sockets[cl_numsockets - 1])
583 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
586 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
588 lhnetaddress_t address;
590 char addressstring2[1024];
591 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
593 if ((s = LHNET_OpenSocket_Connectionless(&address)))
595 cl_sockets[cl_numsockets++] = s;
596 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
597 Con_Printf("Client opened a socket on address %s\n", addressstring2);
601 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
602 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
606 Con_Printf("Client unable to parse address %s\n", addressstring);
609 void NetConn_OpenClientPorts(void)
612 NetConn_CloseClientPorts();
613 port = bound(0, cl_netport.integer, 65535);
614 if (cl_netport.integer != port)
615 Cvar_SetValueQuick(&cl_netport, port);
616 Con_Printf("Client using port %i\n", port);
617 NetConn_OpenClientPort("local:2", 0);
618 NetConn_OpenClientPort(net_address.string, port);
619 //NetConn_OpenClientPort(net_address_ipv6.string, port);
622 void NetConn_CloseServerPorts(void)
624 for (;sv_numsockets > 0;sv_numsockets--)
625 if (sv_sockets[sv_numsockets - 1])
626 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
629 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
631 lhnetaddress_t address;
633 char addressstring2[1024];
634 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
636 if ((s = LHNET_OpenSocket_Connectionless(&address)))
638 sv_sockets[sv_numsockets++] = s;
639 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
640 Con_Printf("Server listening on address %s\n", addressstring2);
644 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
645 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
649 Con_Printf("Server unable to parse address %s\n", addressstring);
652 void NetConn_OpenServerPorts(int opennetports)
655 NetConn_CloseServerPorts();
656 port = bound(0, sv_netport.integer, 65535);
659 Con_Printf("Server using port %i\n", port);
660 if (sv_netport.integer != port)
661 Cvar_SetValueQuick(&sv_netport, port);
662 if (cls.state != ca_dedicated)
663 NetConn_OpenServerPort("local:1", 0);
666 NetConn_OpenServerPort(net_address.string, port);
667 //NetConn_OpenServerPort(net_address_ipv6.string, port);
669 if (sv_numsockets == 0)
670 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
673 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
675 int i, a = LHNETADDRESS_GetAddressType(address);
676 for (i = 0;i < cl_numsockets;i++)
677 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
678 return cl_sockets[i];
682 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
684 int i, a = LHNETADDRESS_GetAddressType(address);
685 for (i = 0;i < sv_numsockets;i++)
686 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
687 return sv_sockets[i];
691 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
694 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
695 conn->mysocket = mysocket;
696 conn->peeraddress = *peeraddress;
697 conn->canSend = true;
698 conn->lastMessageTime = realtime;
699 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
700 // reduce effectiveness of connection request floods
701 conn->timeout = realtime + net_connecttimeout.value;
702 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
703 conn->next = netconn_list;
708 void NetConn_Close(netconn_t *conn)
711 // remove connection from list
712 if (conn == netconn_list)
713 netconn_list = conn->next;
716 for (c = netconn_list;c;c = c->next)
720 c->next = conn->next;
724 // not found in list, we'll avoid crashing here...
732 static int clientport = -1;
733 static int clientport2 = -1;
734 static int hostport = -1;
735 static void NetConn_UpdateServerStuff(void)
737 if (cls.state != ca_dedicated)
739 if (clientport2 != cl_netport.integer)
741 clientport2 = cl_netport.integer;
742 if (cls.state == ca_connected)
743 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
745 if (cls.state == ca_disconnected && clientport != clientport2)
747 clientport = clientport2;
748 NetConn_CloseClientPorts();
750 if (cl_numsockets == 0)
751 NetConn_OpenClientPorts();
754 if (hostport != sv_netport.integer)
756 hostport = sv_netport.integer;
758 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
762 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
766 unsigned int sequence;
771 qlength = (unsigned int)BigLong(((int *)data)[0]);
772 flags = qlength & ~NETFLAG_LENGTH_MASK;
773 qlength &= NETFLAG_LENGTH_MASK;
774 // control packets were already handled
775 if (!(flags & NETFLAG_CTL) && qlength == length)
777 sequence = BigLong(((int *)data)[1]);
781 if (flags & NETFLAG_UNRELIABLE)
783 if (sequence >= conn->unreliableReceiveSequence)
785 if (sequence > conn->unreliableReceiveSequence)
787 count = sequence - conn->unreliableReceiveSequence;
788 droppedDatagrams += count;
789 Con_DPrintf("Dropped %u datagram(s)\n", count);
791 conn->unreliableReceiveSequence = sequence + 1;
792 conn->lastMessageTime = realtime;
793 conn->timeout = realtime + net_messagetimeout.value;
794 unreliableMessagesReceived++;
797 SZ_Clear(&net_message);
798 SZ_Write(&net_message, data, length);
804 Con_DPrint("Got a stale datagram\n");
807 else if (flags & NETFLAG_ACK)
809 if (sequence == (conn->sendSequence - 1))
811 if (sequence == conn->ackSequence)
814 if (conn->ackSequence != conn->sendSequence)
815 Con_DPrint("ack sequencing error\n");
816 conn->lastMessageTime = realtime;
817 conn->timeout = realtime + net_messagetimeout.value;
818 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
819 if (conn->sendMessageLength > 0)
821 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
822 conn->sendNext = true;
823 NetConn_SendMessageNext(conn);
827 conn->sendMessageLength = 0;
828 conn->canSend = true;
832 Con_DPrint("Duplicate ACK received\n");
835 Con_DPrint("Stale ACK received\n");
838 else if (flags & NETFLAG_DATA)
840 unsigned int temppacket[2];
841 temppacket[0] = BigLong(8 | NETFLAG_ACK);
842 temppacket[1] = BigLong(sequence);
843 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
844 if (sequence == conn->receiveSequence)
846 conn->lastMessageTime = realtime;
847 conn->timeout = realtime + net_messagetimeout.value;
848 conn->receiveSequence++;
849 if( conn->receiveMessageLength + length <= sizeof( conn->receiveMessage ) ) {
850 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
851 conn->receiveMessageLength += length;
853 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
854 "Dropping the message!\n", sequence );
855 conn->receiveMessageLength = 0;
858 if (flags & NETFLAG_EOM)
860 reliableMessagesReceived++;
861 length = conn->receiveMessageLength;
862 conn->receiveMessageLength = 0;
865 SZ_Clear(&net_message);
866 SZ_Write(&net_message, conn->receiveMessage, length);
873 receivedDuplicateCount++;
881 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
883 cls.connect_trying = false;
884 M_Update_Return_Reason("");
885 // the connection request succeeded, stop current connection and set up a new connection
887 cls.netcon = NetConn_Open(mysocket, peeraddress);
888 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
891 cls.demonum = -1; // not in the demo loop now
892 cls.state = ca_connected;
893 cls.signon = 0; // need all the signon messages before playing
896 int NetConn_IsLocalGame(void)
898 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
903 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
906 lhnetaddress_t svaddress;
908 char *string, addressstring2[128], cname[128], ipstring[32];
909 char stringbuf[16384];
911 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
913 // received a command string - strip off the packaging and put it
914 // into our string buffer with NULL termination
917 length = min(length, (int)sizeof(stringbuf) - 1);
918 memcpy(stringbuf, data, length);
919 stringbuf[length] = 0;
922 if (developer.integer)
924 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
925 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
926 Com_HexDumpToConsole(data, length);
929 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
931 char protocolnames[1400];
932 Protocol_Names(protocolnames, sizeof(protocolnames));
933 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
934 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
935 M_Update_Return_Reason("Got challenge response");
936 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
939 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
941 M_Update_Return_Reason("Accepted");
942 NetConn_ConnectionEstablished(mysocket, peeraddress);
945 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
947 char rejectreason[32];
948 cls.connect_trying = false;
950 length = max(length - 7, (int)sizeof(rejectreason) - 1);
951 memcpy(rejectreason, string, length);
952 rejectreason[length] = 0;
953 M_Update_Return_Reason(rejectreason);
956 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
958 serverlist_info_t *info;
963 // serverlist only uses text addresses
964 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
965 // search the cache for this server and update it
966 for( n = 0; n < serverlist_cachecount; n++ )
967 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
969 if( n == serverlist_cachecount ) {
970 // LAN search doesnt require an answer from the master server so we wont
971 // know the ping nor will it be initialized already...
974 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
978 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
979 // store the data the engine cares about (address and ping)
980 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
981 serverlist_cache[serverlist_cachecount].info.ping = 100000;
982 serverlist_cache[serverlist_cachecount].querytime = realtime;
983 // if not in the slist menu we should print the server to console
984 if (serverlist_consoleoutput) {
985 Con_Printf("querying %s\n", ipstring);
988 ++serverlist_cachecount;
991 info = &serverlist_cache[n].info;
992 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
993 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
994 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
995 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
996 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
997 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
998 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1000 if (info->ping == 100000)
1003 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1004 pingtime = bound(0, pingtime, 9999);
1006 info->ping = pingtime;
1008 // legacy/old stuff move it to the menu ASAP
1010 // build description strings for the things users care about
1011 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);
1012 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);
1013 // if ping is especially high, display it as such
1014 if (pingtime >= 300)
1016 // orange numbers (lower block)
1017 for (i = 0;i < 5;i++)
1018 if (serverlist_cache[n].line1[i] != ' ')
1019 serverlist_cache[n].line1[i] += 128;
1021 else if (pingtime >= 200)
1023 // yellow numbers (in upper block)
1024 for (i = 0;i < 5;i++)
1025 if (serverlist_cache[n].line1[i] != ' ')
1026 serverlist_cache[n].line1[i] -= 30;
1028 // and finally, update the view set
1029 if( serverlist_cache[n].finished )
1030 ServerList_ViewList_Remove( &serverlist_cache[n] );
1031 // else if not in the slist menu we should print the server to console (if wanted)
1032 else if( serverlist_consoleoutput )
1033 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1034 ServerList_ViewList_Insert( &serverlist_cache[n] );
1035 serverlist_cache[n].finished = true;
1039 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1041 // Extract the IP addresses
1045 if (serverlist_consoleoutput)
1046 Con_Print("received server list...\n");
1047 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1051 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1052 if (developer.integer)
1053 Con_Printf("Requesting info from server %s\n", ipstring);
1054 // ignore the rest of the message if the serverlist is full
1055 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1057 // also ignore it if we have already queried it (other master server response)
1058 for( n = 0 ; n < serverlist_cachecount ; n++ )
1059 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1061 if( n >= serverlist_cachecount )
1065 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
1066 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
1068 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1069 // store the data the engine cares about (address and ping)
1070 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1071 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1072 serverlist_cache[serverlist_cachecount].querytime = realtime;
1073 // if not in the slist menu we should print the server to console
1074 if (serverlist_consoleoutput)
1075 Con_Printf("querying %s\n", ipstring);
1077 ++serverlist_cachecount;
1080 // move on to next address in packet
1087 if (!strncmp(string, "ping", 4))
1089 if (developer.integer)
1090 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1091 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1094 if (!strncmp(string, "ack", 3))
1097 // we may not have liked the packet, but it was a command packet, so
1098 // we're done processing this packet now
1101 // netquake control packets, supported for compatibility only
1102 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1107 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1111 if (developer.integer)
1112 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1113 if (cls.connect_trying)
1115 lhnetaddress_t clientportaddress;
1116 clientportaddress = *peeraddress;
1119 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1122 LHNETADDRESS_SetPort(&clientportaddress, port);
1124 M_Update_Return_Reason("Accepted");
1125 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1129 if (developer.integer)
1130 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1131 cls.connect_trying = false;
1132 M_Update_Return_Reason(data);
1135 case CCREP_SERVER_INFO:
1136 if (developer.integer)
1137 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1138 if (cls.state != ca_dedicated)
1140 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1141 // string we just ignore it and keep the real address
1143 // serverlist only uses text addresses
1144 cname = UDP_AddrToString(readaddr);
1145 // search the cache for this server
1146 for (n = 0; n < hostCacheCount; n++)
1147 if (!strcmp(cname, serverlist[n].cname))
1150 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1153 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1154 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1155 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1156 serverlist[n].users = MSG_ReadByte();
1157 serverlist[n].maxusers = MSG_ReadByte();
1159 if (c != NET_PROTOCOL_VERSION)
1161 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1162 strcpy(serverlist[n].name, "*");
1163 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1165 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1169 case CCREP_PLAYER_INFO:
1170 // we got a CCREP_PLAYER_INFO??
1171 //if (developer.integer)
1172 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1174 case CCREP_RULE_INFO:
1175 // we got a CCREP_RULE_INFO??
1176 //if (developer.integer)
1177 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1183 // we may not have liked the packet, but it was a valid control
1184 // packet, so we're done processing this packet now
1188 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)
1189 CL_ParseServerMessage();
1193 void NetConn_ClientFrame(void)
1196 lhnetaddress_t peeraddress;
1198 NetConn_UpdateServerStuff();
1199 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1201 if (cls.connect_remainingtries == 0)
1202 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1203 cls.connect_nextsendtime = realtime + 1;
1204 cls.connect_remainingtries--;
1205 if (cls.connect_remainingtries <= -10)
1207 cls.connect_trying = false;
1208 M_Update_Return_Reason("Connect: Failed");
1211 // try challenge first (newer server)
1212 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1213 // then try netquake as a fallback (old server, or netquake)
1214 SZ_Clear(&net_message);
1215 // save space for the header, filled in later
1216 MSG_WriteLong(&net_message, 0);
1217 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1218 MSG_WriteString(&net_message, "QUAKE");
1219 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1220 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1221 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1222 SZ_Clear(&net_message);
1224 for (i = 0;i < cl_numsockets;i++)
1225 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1226 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1227 if (cls.netcon && realtime > cls.netcon->timeout)
1229 Con_Print("Connection timed out\n");
1231 Host_ShutdownServer (false);
1233 for (conn = netconn_list;conn;conn = conn->next)
1234 NetConn_ReSendMessage(conn);
1237 #define MAX_CHALLENGES 128
1240 lhnetaddress_t address;
1244 challenge[MAX_CHALLENGES];
1246 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1250 for (i = 0;i < bufferlength - 1;i++)
1254 c = rand () % (127 - 33) + 33;
1255 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1261 extern void SV_SendServerinfo (client_t *client);
1262 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1264 int i, n, ret, clientnum, responselength, best;
1268 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1272 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1274 // received a command string - strip off the packaging and put it
1275 // into our string buffer with NULL termination
1278 length = min(length, (int)sizeof(stringbuf) - 1);
1279 memcpy(stringbuf, data, length);
1280 stringbuf[length] = 0;
1283 if (developer.integer)
1285 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1286 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1287 Com_HexDumpToConsole(data, length);
1290 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1292 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1294 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1296 if (besttime > challenge[i].time)
1297 besttime = challenge[best = i].time;
1299 // if we did not find an exact match, choose the oldest and
1300 // update address and string
1301 if (i == MAX_CHALLENGES)
1304 challenge[i].address = *peeraddress;
1305 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1307 challenge[i].time = realtime;
1308 // send the challenge
1309 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1312 if (length > 8 && !memcmp(string, "connect\\", 8))
1316 if ((s = SearchInfostring(string, "challenge")))
1318 // validate the challenge
1319 for (i = 0;i < MAX_CHALLENGES;i++)
1320 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1322 if (i < MAX_CHALLENGES)
1324 // check engine protocol
1325 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1327 if (developer.integer)
1328 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1329 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1333 // see if this is a duplicate connection request
1334 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1335 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1337 if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1339 // client is still trying to connect,
1340 // so we send a duplicate reply
1341 if (developer.integer)
1342 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1343 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1346 else if (clientnum < svs.maxclients)
1348 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1350 // client crashed and is coming back, keep their stuff intact
1351 SV_SendServerinfo(client);
1352 //host_client = client;
1353 //SV_DropClient (true);
1360 // this is a new client, find a slot
1361 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1362 if (!client->active)
1364 if (clientnum < svs.maxclients)
1366 // prepare the client struct
1367 if ((conn = NetConn_Open(mysocket, peeraddress)))
1369 // allocated connection
1370 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1371 if (developer.integer)
1372 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1373 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1374 // now set up the client
1375 SV_ConnectClient(clientnum, conn);
1376 NetConn_Heartbeat(1);
1382 if (developer.integer)
1383 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1384 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1392 if (length >= 7 && !memcmp(string, "getinfo", 7))
1394 const char *challenge = NULL;
1395 // If there was a challenge in the getinfo message
1396 if (length > 8 && string[7] == ' ')
1397 challenge = string + 8;
1398 for (i = 0, n = 0;i < svs.maxclients;i++)
1399 if (svs.clients[i].active)
1401 responselength = dpsnprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1402 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1403 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1404 gamename, com_modname, svs.maxclients, n,
1405 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1406 // does it fit in the buffer?
1407 if (responselength >= 0)
1409 if (developer.integer)
1410 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1411 NetConn_WriteString(mysocket, response, peeraddress);
1416 if (!strncmp(string, "ping", 4))
1418 if (developer.integer)
1419 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1420 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1423 if (!strncmp(string, "ack", 3))
1426 // we may not have liked the packet, but it was a command packet, so
1427 // we're done processing this packet now
1430 // LordHavoc: disabled netquake control packet support in server
1434 // netquake control packets, supported for compatibility only
1435 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1440 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1444 //if (developer.integer)
1445 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1446 if (length >= (int)strlen("QUAKE") + 1 + 1)
1448 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1450 if (developer.integer)
1451 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1452 SZ_Clear(&net_message);
1453 // save space for the header, filled in later
1454 MSG_WriteLong(&net_message, 0);
1455 MSG_WriteByte(&net_message, CCREP_REJECT);
1456 MSG_WriteString(&net_message, "Incompatible version.\n");
1457 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1458 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1459 SZ_Clear(&net_message);
1463 // see if this is a duplicate connection request
1464 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1465 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1467 if (clientnum < svs.maxclients)
1469 // duplicate connection request
1470 if (realtime - client->connecttime < 2.0)
1472 // client is still trying to connect,
1473 // so we send a duplicate reply
1474 if (developer.integer)
1475 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1476 SZ_Clear(&net_message);
1477 // save space for the header, filled in later
1478 MSG_WriteLong(&net_message, 0);
1479 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1480 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1481 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1482 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1483 SZ_Clear(&net_message);
1486 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1488 SV_SendServerinfo(client);
1489 // the old client hasn't sent us anything
1490 // in quite a while, so kick off and let
1491 // the retry take care of it...
1492 //host_client = client;
1493 //SV_DropClient (true);
1499 // this is a new client, find a slot
1500 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1501 if (!client->active)
1503 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1505 // connect to the client
1506 // everything is allocated, just fill in the details
1507 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1508 if (developer.integer)
1509 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1510 // send back the info about the server connection
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_ACCEPT);
1515 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1516 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1517 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1518 SZ_Clear(&net_message);
1519 // now set up the client struct
1520 SV_ConnectClient(clientnum, conn);
1521 NetConn_Heartbeat(1);
1525 //if (developer.integer)
1526 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1527 // no room; try to let player know
1528 SZ_Clear(&net_message);
1529 // save space for the header, filled in later
1530 MSG_WriteLong(&net_message, 0);
1531 MSG_WriteByte(&net_message, CCREP_REJECT);
1532 MSG_WriteString(&net_message, "Server is full.\n");
1533 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1534 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1535 SZ_Clear(&net_message);
1542 case CCREQ_SERVER_INFO:
1543 if (developer.integer)
1544 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1545 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1547 if (developer.integer)
1548 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1549 SZ_Clear(&net_message);
1550 // save space for the header, filled in later
1551 MSG_WriteLong(&net_message, 0);
1552 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1553 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1554 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1555 MSG_WriteString(&net_message, hostname.string);
1556 MSG_WriteString(&net_message, sv.name);
1557 MSG_WriteByte(&net_message, net_activeconnections);
1558 MSG_WriteByte(&net_message, svs.maxclients);
1559 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1560 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1561 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1562 SZ_Clear(&net_message);
1565 case CCREQ_PLAYER_INFO:
1566 if (developer.integer)
1567 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1570 int playerNumber, activeNumber, clientNumber;
1573 playerNumber = MSG_ReadByte();
1575 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1576 if (client->active && ++activeNumber == playerNumber)
1578 if (clientNumber != svs.maxclients)
1580 SZ_Clear(&net_message);
1581 // save space for the header, filled in later
1582 MSG_WriteLong(&net_message, 0);
1583 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1584 MSG_WriteByte(&net_message, playerNumber);
1585 MSG_WriteString(&net_message, client->name);
1586 MSG_WriteLong(&net_message, client->colors);
1587 MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1588 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1589 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1590 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1591 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1592 SZ_Clear(&net_message);
1596 case CCREQ_RULE_INFO:
1597 if (developer.integer)
1598 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1604 // find the search start location
1605 prevCvarName = MSG_ReadString();
1606 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1608 // send the response
1609 SZ_Clear(&net_message);
1610 // save space for the header, filled in later
1611 MSG_WriteLong(&net_message, 0);
1612 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1615 MSG_WriteString(&net_message, var->name);
1616 MSG_WriteString(&net_message, var->string);
1618 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1619 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1620 SZ_Clear(&net_message);
1627 // we may not have liked the packet, but it was a valid control
1628 // packet, so we're done processing this packet now
1633 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1635 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1637 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1638 SV_ReadClientMessage();
1646 void NetConn_ServerFrame(void)
1649 lhnetaddress_t peeraddress;
1651 NetConn_UpdateServerStuff();
1652 for (i = 0;i < sv_numsockets;i++)
1653 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1654 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1655 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1657 // never timeout loopback connections
1658 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1660 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1661 SV_DropClient(false);
1664 for (conn = netconn_list;conn;conn = conn->next)
1665 NetConn_ReSendMessage(conn);
1668 void NetConn_QueryMasters(void)
1672 lhnetaddress_t masteraddress;
1673 lhnetaddress_t broadcastaddress;
1676 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1679 // 26000 is the default quake server port, servers on other ports will not
1681 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1682 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1684 for (i = 0;i < cl_numsockets;i++)
1688 // search LAN for Quake servers
1689 SZ_Clear(&net_message);
1690 // save space for the header, filled in later
1691 MSG_WriteLong(&net_message, 0);
1692 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1693 MSG_WriteString(&net_message, "QUAKE");
1694 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1695 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1696 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1697 SZ_Clear(&net_message);
1699 // search LAN for DarkPlaces servers
1700 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1702 // build the getservers message to send to the master servers
1703 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1706 for (masternum = 0;sv_masters[masternum].name;masternum++)
1708 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1711 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1716 if (!masterquerycount)
1718 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1719 M_Update_Return_Reason("No network");
1723 void NetConn_Heartbeat(int priority)
1725 lhnetaddress_t masteraddress;
1727 lhnetsocket_t *mysocket;
1729 // if it's a state change (client connected), limit next heartbeat to no
1730 // more than 30 sec in the future
1731 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1732 nextheartbeattime = realtime + 30.0;
1734 // limit heartbeatperiod to 30 to 270 second range,
1735 // lower limit is to avoid abusing master servers with excess traffic,
1736 // upper limit is to avoid timing out on the master server (which uses
1738 if (sv_heartbeatperiod.value < 30)
1739 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1740 if (sv_heartbeatperiod.value > 270)
1741 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1743 // make advertising optional and don't advertise singleplayer games, and
1744 // only send a heartbeat as often as the admin wants
1745 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1747 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1748 for (masternum = 0;sv_masters[masternum].name;masternum++)
1749 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1750 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1754 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1757 qbyte sent[MAX_SCOREBOARD];
1759 memset(sent, 0, sizeof(sent));
1761 // simultaneously wait for the first CanSendMessage and send the message,
1762 // then wait for a second CanSendMessage (verifying it was received), or
1763 // the client drops and is no longer counted
1764 // the loop aborts when either it runs out of clients to send to, or a
1766 blocktime += Sys_DoubleTime();
1770 NetConn_ClientFrame();
1771 NetConn_ServerFrame();
1772 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1774 if (host_client->netconnection)
1776 if (NetConn_CanSendMessage(host_client->netconnection))
1779 NetConn_SendReliableMessage(host_client->netconnection, data);
1782 if (!NetConn_CanSendMessage(host_client->netconnection))
1787 while (count && Sys_DoubleTime() < blocktime);
1791 static void Net_Heartbeat_f(void)
1794 NetConn_Heartbeat(2);
1796 Con_Print("No server running, can not heartbeat to master server.\n");
1799 void PrintStats(netconn_t *conn)
1801 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1804 void Net_Stats_f(void)
1807 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1808 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1809 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1810 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1811 Con_Printf("packetsSent = %i\n", packetsSent);
1812 Con_Printf("packetsReSent = %i\n", packetsReSent);
1813 Con_Printf("packetsReceived = %i\n", packetsReceived);
1814 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1815 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1816 Con_Print("connections =\n");
1817 for (conn = netconn_list;conn;conn = conn->next)
1821 void Net_Slist_f(void)
1823 ServerList_ResetMasks();
1824 serverlist_sortbyfield = SLIF_PING;
1825 serverlist_sortdescending = false;
1826 if (m_state != m_slist) {
1827 Con_Print("Sending requests to master servers\n");
1828 ServerList_QueryList();
1829 serverlist_consoleoutput = true;
1830 Con_Print("Listening for replies...\n");
1832 ServerList_QueryList();
1835 void NetConn_Init(void)
1838 lhnetaddress_t tempaddress;
1839 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
1840 Cmd_AddCommand("net_stats", Net_Stats_f);
1841 Cmd_AddCommand("net_slist", Net_Slist_f);
1842 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1843 Cvar_RegisterVariable(&net_messagetimeout);
1844 Cvar_RegisterVariable(&net_messagerejointimeout);
1845 Cvar_RegisterVariable(&net_connecttimeout);
1846 Cvar_RegisterVariable(&cl_netlocalping);
1847 Cvar_RegisterVariable(&cl_netpacketloss);
1848 Cvar_RegisterVariable(&hostname);
1849 Cvar_RegisterVariable(&developer_networking);
1850 Cvar_RegisterVariable(&cl_netport);
1851 Cvar_RegisterVariable(&sv_netport);
1852 Cvar_RegisterVariable(&net_address);
1853 //Cvar_RegisterVariable(&net_address_ipv6);
1854 Cvar_RegisterVariable(&sv_public);
1855 Cvar_RegisterVariable(&sv_heartbeatperiod);
1856 for (i = 0;sv_masters[i].name;i++)
1857 Cvar_RegisterVariable(&sv_masters[i]);
1858 // 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.
1859 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1861 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1863 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1864 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1867 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1869 // 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
1870 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1872 i = atoi(com_argv[i + 1]);
1873 if (i >= 0 && i < 65536)
1875 Con_Printf("-port option used, setting port cvar to %i\n", i);
1876 Cvar_SetValueQuick(&sv_netport, i);
1879 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1883 net_message.data = net_message_buf;
1884 net_message.maxsize = sizeof(net_message_buf);
1885 net_message.cursize = 0;
1889 void NetConn_Shutdown(void)
1891 NetConn_CloseClientPorts();
1892 NetConn_CloseServerPorts();