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"};
57 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20"};
58 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4"};
59 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4"};
60 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3"};
62 /* statistic counters */
63 static int packetsSent = 0;
64 static int packetsReSent = 0;
65 static int packetsReceived = 0;
66 static int receivedDuplicateCount = 0;
67 static int droppedDatagrams = 0;
69 static int unreliableMessagesSent = 0;
70 static int unreliableMessagesReceived = 0;
71 static int reliableMessagesSent = 0;
72 static int reliableMessagesReceived = 0;
74 double masterquerytime = -1000;
75 int masterquerycount = 0;
76 int masterreplycount = 0;
77 int serverquerycount = 0;
78 int serverreplycount = 0;
80 // this is only false if there are still servers left to query
81 int serverlist_querysleep = true;
83 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
84 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
87 lhnetsocket_t *cl_sockets[16];
89 lhnetsocket_t *sv_sockets[16];
91 netconn_t *netconn_list = NULL;
92 mempool_t *netconn_mempool = NULL;
94 cvar_t cl_netport = {0, "cl_port", "0"};
95 cvar_t sv_netport = {0, "port", "26000"};
96 cvar_t net_address = {0, "net_address", "0.0.0.0"};
97 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
99 // ServerList interface
100 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
101 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
103 serverlist_infofield_t serverlist_sortbyfield;
104 qboolean serverlist_sortdescending;
106 int serverlist_viewcount = 0;
107 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
109 int serverlist_cachecount;
110 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
112 qboolean serverlist_consoleoutput;
114 // helper function to insert a value into the viewset
115 // spare entries will be removed
116 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
119 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
120 i = serverlist_viewcount++;
122 i = SERVERLIST_VIEWLISTSIZE - 1;
125 for( ; i > index ; i-- )
126 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
128 serverlist_viewlist[index] = entry;
131 // we suppose serverlist_viewcount to be valid, ie > 0
132 static void _ServerList_ViewList_Helper_Remove( int index )
134 serverlist_viewcount--;
135 for( ; index < serverlist_viewcount ; index++ )
136 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
139 // returns true if A should be inserted before B
140 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
142 int result = 0; // > 0 if for numbers A > B and for text if A < B
144 switch( serverlist_sortbyfield ) {
146 result = A->info.ping - B->info.ping;
148 case SLIF_MAXPLAYERS:
149 result = A->info.maxplayers - B->info.maxplayers;
151 case SLIF_NUMPLAYERS:
152 result = A->info.numplayers - B->info.numplayers;
155 result = A->info.protocol - B->info.protocol;
158 result = strcmp( B->info.cname, A->info.cname );
161 result = strcmp( B->info.game, A->info.game );
164 result = strcmp( B->info.map, A->info.map );
167 result = strcmp( B->info.mod, A->info.mod );
170 result = strcmp( B->info.name, A->info.name );
173 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
177 if( serverlist_sortdescending )
182 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
184 // This should actually be done with some intermediate and end-of-function return
196 case SLMO_GREATEREQUAL:
198 case SLMO_NOTCONTAIN:
201 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
206 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
208 // Same here, also using an intermediate & final return would be more appropriate
212 return *B && !!strstr( A, B ); // we want a real bool
213 case SLMO_NOTCONTAIN:
214 return !*B || !strstr( A, B );
216 return strcmp( A, B ) < 0;
218 return strcmp( A, B ) <= 0;
220 return strcmp( A, B ) == 0;
222 return strcmp( A, B ) > 0;
224 return strcmp( A, B ) != 0;
225 case SLMO_GREATEREQUAL:
226 return strcmp( A, B ) >= 0;
228 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
233 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
235 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
237 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
239 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
241 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
243 if( *mask->info.cname
244 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
247 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
250 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
253 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
256 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
261 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
265 // FIXME: change this to be more readable (...)
266 // now check whether it passes through the masks
267 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
268 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
271 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
272 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
274 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
277 if( !serverlist_viewcount ) {
278 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
281 // ok, insert it, we just need to find out where exactly:
284 // check whether to insert it as new first item
285 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
286 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
288 } // check whether to insert it as new last item
289 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
290 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
294 end = serverlist_viewcount - 1;
295 while( end > start + 1 )
297 mid = (start + end) / 2;
298 // test the item that lies in the middle between start and end
299 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
300 // the item has to be in the upper half
303 // the item has to be in the lower half
306 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
309 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
312 for( i = 0; i < serverlist_viewcount; i++ )
314 if (serverlist_viewlist[i] == entry)
316 _ServerList_ViewList_Helper_Remove(i);
322 void ServerList_RebuildViewList(void)
326 serverlist_viewcount = 0;
327 for( i = 0 ; i < serverlist_cachecount ; i++ )
328 if( serverlist_cache[i].query == SQS_QUERIED )
329 ServerList_ViewList_Insert( &serverlist_cache[i] );
332 void ServerList_ResetMasks(void)
334 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
335 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
339 static void _ServerList_Test(void)
342 for( i = 0 ; i < 1024 ; i++ ) {
343 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
344 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
345 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, 128, "Black's ServerList Test %i", i );
346 serverlist_cache[serverlist_cachecount].finished = true;
347 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
348 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
349 serverlist_cachecount++;
354 void ServerList_QueryList(void)
356 masterquerytime = realtime;
357 masterquerycount = 0;
358 masterreplycount = 0;
359 serverquerycount = 0;
360 serverreplycount = 0;
361 serverlist_cachecount = 0;
362 serverlist_viewcount = 0;
363 serverlist_consoleoutput = false;
365 //_ServerList_Test();
367 NetConn_QueryMasters();
372 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
374 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
378 if (cl_netpacketloss.integer)
379 for (i = 0;i < cl_numsockets;i++)
380 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
382 if (developer_networking.integer)
384 char addressstring[128], addressstring2[128];
385 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
388 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
389 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
390 Com_HexDumpToConsole(data, length);
393 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
398 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
402 if (cl_netpacketloss.integer)
403 for (i = 0;i < cl_numsockets;i++)
404 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
406 ret = LHNET_Write(mysocket, data, length, peeraddress);
407 if (developer_networking.integer)
409 char addressstring[128], addressstring2[128];
410 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
411 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
412 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
413 Com_HexDumpToConsole(data, length);
418 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
420 // note this does not include the trailing NULL because we add that in the parser
421 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
424 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
426 unsigned int packetLen;
427 unsigned int dataLen;
429 unsigned int *header;
432 if (data->cursize == 0)
433 Sys_Error("Datagram_SendMessage: zero length message\n");
435 if (data->cursize > (int)sizeof(conn->sendMessage))
436 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
438 if (conn->canSend == false)
439 Sys_Error("SendMessage: called with canSend == false\n");
442 memcpy(conn->sendMessage, data->data, data->cursize);
443 conn->sendMessageLength = data->cursize;
445 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
447 dataLen = conn->sendMessageLength;
452 dataLen = MAX_PACKETFRAGMENT;
456 packetLen = NET_HEADERSIZE + dataLen;
458 header = (void *)sendbuffer;
459 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
460 header[1] = BigLong(conn->sendSequence);
461 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
463 conn->sendSequence++;
464 conn->canSend = false;
466 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
469 conn->lastSendTime = realtime;
471 reliableMessagesSent++;
475 static void NetConn_SendMessageNext(netconn_t *conn)
477 unsigned int packetLen;
478 unsigned int dataLen;
480 unsigned int *header;
482 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
484 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
486 dataLen = conn->sendMessageLength;
491 dataLen = MAX_PACKETFRAGMENT;
495 packetLen = NET_HEADERSIZE + dataLen;
497 header = (void *)sendbuffer;
498 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
499 header[1] = BigLong(conn->sendSequence);
500 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
502 conn->sendSequence++;
503 conn->sendNext = false;
505 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
508 conn->lastSendTime = realtime;
513 static void NetConn_ReSendMessage(netconn_t *conn)
515 unsigned int packetLen;
516 unsigned int dataLen;
518 unsigned int *header;
520 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
522 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
524 dataLen = conn->sendMessageLength;
529 dataLen = MAX_PACKETFRAGMENT;
533 packetLen = NET_HEADERSIZE + dataLen;
535 header = (void *)sendbuffer;
536 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
537 header[1] = BigLong(conn->sendSequence - 1);
538 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
540 conn->sendNext = false;
542 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
545 conn->lastSendTime = realtime;
550 qboolean NetConn_CanSendMessage(netconn_t *conn)
552 return conn->canSend;
555 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
560 packetLen = NET_HEADERSIZE + data->cursize;
563 if (data->cursize == 0)
564 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
566 if (packetLen > (int)sizeof(sendbuffer))
567 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
570 header = (void *)sendbuffer;
571 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
572 header[1] = BigLong(conn->unreliableSendSequence);
573 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
575 conn->unreliableSendSequence++;
577 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
581 unreliableMessagesSent++;
585 void NetConn_CloseClientPorts(void)
587 for (;cl_numsockets > 0;cl_numsockets--)
588 if (cl_sockets[cl_numsockets - 1])
589 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
592 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
594 lhnetaddress_t address;
596 char addressstring2[1024];
597 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
599 if ((s = LHNET_OpenSocket_Connectionless(&address)))
601 cl_sockets[cl_numsockets++] = s;
602 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
603 Con_Printf("Client opened a socket on address %s\n", addressstring2);
607 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
608 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
612 Con_Printf("Client unable to parse address %s\n", addressstring);
615 void NetConn_OpenClientPorts(void)
618 NetConn_CloseClientPorts();
619 port = bound(0, cl_netport.integer, 65535);
620 if (cl_netport.integer != port)
621 Cvar_SetValueQuick(&cl_netport, port);
622 Con_Printf("Client using port %i\n", port);
623 NetConn_OpenClientPort("local:2", 0);
624 NetConn_OpenClientPort(net_address.string, port);
625 //NetConn_OpenClientPort(net_address_ipv6.string, port);
628 void NetConn_CloseServerPorts(void)
630 for (;sv_numsockets > 0;sv_numsockets--)
631 if (sv_sockets[sv_numsockets - 1])
632 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
635 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
637 lhnetaddress_t address;
639 char addressstring2[1024];
640 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
642 if ((s = LHNET_OpenSocket_Connectionless(&address)))
644 sv_sockets[sv_numsockets++] = s;
645 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
646 Con_Printf("Server listening on address %s\n", addressstring2);
650 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
651 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
655 Con_Printf("Server unable to parse address %s\n", addressstring);
658 void NetConn_OpenServerPorts(int opennetports)
661 NetConn_CloseServerPorts();
662 port = bound(0, sv_netport.integer, 65535);
665 Con_Printf("Server using port %i\n", port);
666 if (sv_netport.integer != port)
667 Cvar_SetValueQuick(&sv_netport, port);
668 if (cls.state != ca_dedicated)
669 NetConn_OpenServerPort("local:1", 0);
672 NetConn_OpenServerPort(net_address.string, port);
673 //NetConn_OpenServerPort(net_address_ipv6.string, port);
675 if (sv_numsockets == 0)
676 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
679 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
681 int i, a = LHNETADDRESS_GetAddressType(address);
682 for (i = 0;i < cl_numsockets;i++)
683 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
684 return cl_sockets[i];
688 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
690 int i, a = LHNETADDRESS_GetAddressType(address);
691 for (i = 0;i < sv_numsockets;i++)
692 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
693 return sv_sockets[i];
697 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
700 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
701 conn->mysocket = mysocket;
702 conn->peeraddress = *peeraddress;
703 conn->canSend = true;
704 conn->lastMessageTime = realtime;
705 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
706 // reduce effectiveness of connection request floods
707 conn->timeout = realtime + net_connecttimeout.value;
708 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
709 conn->next = netconn_list;
714 void NetConn_Close(netconn_t *conn)
717 // remove connection from list
718 if (conn == netconn_list)
719 netconn_list = conn->next;
722 for (c = netconn_list;c;c = c->next)
726 c->next = conn->next;
730 // not found in list, we'll avoid crashing here...
738 static int clientport = -1;
739 static int clientport2 = -1;
740 static int hostport = -1;
741 static void NetConn_UpdateServerStuff(void)
743 if (cls.state != ca_dedicated)
745 if (clientport2 != cl_netport.integer)
747 clientport2 = cl_netport.integer;
748 if (cls.state == ca_connected)
749 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
751 if (cls.state == ca_disconnected && clientport != clientport2)
753 clientport = clientport2;
754 NetConn_CloseClientPorts();
756 if (cl_numsockets == 0)
757 NetConn_OpenClientPorts();
760 if (hostport != sv_netport.integer)
762 hostport = sv_netport.integer;
764 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
768 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
772 unsigned int sequence;
777 qlength = (unsigned int)BigLong(((int *)data)[0]);
778 flags = qlength & ~NETFLAG_LENGTH_MASK;
779 qlength &= NETFLAG_LENGTH_MASK;
780 // control packets were already handled
781 if (!(flags & NETFLAG_CTL) && qlength == length)
783 sequence = BigLong(((int *)data)[1]);
787 if (flags & NETFLAG_UNRELIABLE)
789 if (sequence >= conn->unreliableReceiveSequence)
791 if (sequence > conn->unreliableReceiveSequence)
793 count = sequence - conn->unreliableReceiveSequence;
794 droppedDatagrams += count;
795 Con_DPrintf("Dropped %u datagram(s)\n", count);
797 conn->unreliableReceiveSequence = sequence + 1;
798 conn->lastMessageTime = realtime;
799 conn->timeout = realtime + net_messagetimeout.value;
800 unreliableMessagesReceived++;
803 SZ_Clear(&net_message);
804 SZ_Write(&net_message, data, length);
810 Con_DPrint("Got a stale datagram\n");
813 else if (flags & NETFLAG_ACK)
815 if (sequence == (conn->sendSequence - 1))
817 if (sequence == conn->ackSequence)
820 if (conn->ackSequence != conn->sendSequence)
821 Con_DPrint("ack sequencing error\n");
822 conn->lastMessageTime = realtime;
823 conn->timeout = realtime + net_messagetimeout.value;
824 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
825 if (conn->sendMessageLength > 0)
827 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
828 conn->sendNext = true;
829 NetConn_SendMessageNext(conn);
833 conn->sendMessageLength = 0;
834 conn->canSend = true;
838 Con_DPrint("Duplicate ACK received\n");
841 Con_DPrint("Stale ACK received\n");
844 else if (flags & NETFLAG_DATA)
846 unsigned int temppacket[2];
847 temppacket[0] = BigLong(8 | NETFLAG_ACK);
848 temppacket[1] = BigLong(sequence);
849 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
850 if (sequence == conn->receiveSequence)
852 conn->lastMessageTime = realtime;
853 conn->timeout = realtime + net_messagetimeout.value;
854 conn->receiveSequence++;
855 if( conn->receiveMessageLength + length <= sizeof( conn->receiveMessage ) ) {
856 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
857 conn->receiveMessageLength += length;
859 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
860 "Dropping the message!\n", sequence );
861 conn->receiveMessageLength = 0;
864 if (flags & NETFLAG_EOM)
866 reliableMessagesReceived++;
867 length = conn->receiveMessageLength;
868 conn->receiveMessageLength = 0;
871 SZ_Clear(&net_message);
872 SZ_Write(&net_message, conn->receiveMessage, length);
879 receivedDuplicateCount++;
887 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
889 cls.connect_trying = false;
890 M_Update_Return_Reason("");
891 // the connection request succeeded, stop current connection and set up a new connection
893 // if we're connecting to a remote server, shut down any local server
894 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
895 Host_ShutdownServer (false);
896 // allocate a net connection to keep track of things
897 cls.netcon = NetConn_Open(mysocket, peeraddress);
898 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
901 cls.demonum = -1; // not in the demo loop now
902 cls.state = ca_connected;
903 cls.signon = 0; // need all the signon messages before playing
906 int NetConn_IsLocalGame(void)
908 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
913 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
917 char *string, addressstring2[128], cname[128], ipstring[32];
918 char stringbuf[16384];
920 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
922 // received a command string - strip off the packaging and put it
923 // into our string buffer with NULL termination
926 length = min(length, (int)sizeof(stringbuf) - 1);
927 memcpy(stringbuf, data, length);
928 stringbuf[length] = 0;
931 if (developer.integer)
933 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
934 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
935 Com_HexDumpToConsole(data, length);
938 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
940 char protocolnames[1400];
941 Protocol_Names(protocolnames, sizeof(protocolnames));
942 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
943 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
944 M_Update_Return_Reason("Got challenge response");
945 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
948 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
950 M_Update_Return_Reason("Accepted");
951 NetConn_ConnectionEstablished(mysocket, peeraddress);
954 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
956 char rejectreason[32];
957 cls.connect_trying = false;
959 length = max(length - 7, (int)sizeof(rejectreason) - 1);
960 memcpy(rejectreason, string, length);
961 rejectreason[length] = 0;
962 M_Update_Return_Reason(rejectreason);
965 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
967 serverlist_info_t *info;
972 // serverlist only uses text addresses
973 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
974 // search the cache for this server and update it
975 for( n = 0; n < serverlist_cachecount; n++ )
976 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
978 if( n == serverlist_cachecount ) {
979 // LAN search doesnt require an answer from the master server so we wont
980 // know the ping nor will it be initialized already...
983 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
986 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
987 // store the data the engine cares about (address and ping)
988 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
989 serverlist_cache[serverlist_cachecount].info.ping = 100000;
990 serverlist_cache[serverlist_cachecount].querytime = realtime;
991 // if not in the slist menu we should print the server to console
992 if (serverlist_consoleoutput) {
993 Con_Printf("querying %s\n", ipstring);
996 ++serverlist_cachecount;
999 info = &serverlist_cache[n].info;
1000 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1001 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1002 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1003 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1004 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1005 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1006 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1008 if (info->ping == 100000)
1011 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1012 pingtime = bound(0, pingtime, 9999);
1014 info->ping = pingtime;
1016 // legacy/old stuff move it to the menu ASAP
1018 // build description strings for the things users care about
1019 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);
1020 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);
1021 // if ping is especially high, display it as such
1022 if (pingtime >= 300)
1024 // orange numbers (lower block)
1025 for (i = 0;i < 5;i++)
1026 if (serverlist_cache[n].line1[i] != ' ')
1027 serverlist_cache[n].line1[i] += 128;
1029 else if (pingtime >= 200)
1031 // yellow numbers (in upper block)
1032 for (i = 0;i < 5;i++)
1033 if (serverlist_cache[n].line1[i] != ' ')
1034 serverlist_cache[n].line1[i] -= 30;
1036 if( serverlist_cache[n].query == SQS_QUERIED ) {
1037 ServerList_ViewList_Remove( &serverlist_cache[n] );
1039 // if not in the slist menu we should print the server to console (if wanted)
1040 else if( serverlist_consoleoutput )
1041 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1042 // and finally, update the view set
1043 ServerList_ViewList_Insert( &serverlist_cache[n] );
1044 serverlist_cache[n].query = SQS_QUERIED;
1048 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1050 // Extract the IP addresses
1054 if (serverlist_consoleoutput)
1055 Con_Print("received server list...\n");
1056 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1060 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1061 if (developer.integer)
1062 Con_Printf("Requesting info from server %s\n", ipstring);
1063 // ignore the rest of the message if the serverlist is full
1064 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1066 // also ignore it if we have already queried it (other master server response)
1067 for( n = 0 ; n < serverlist_cachecount ; n++ )
1068 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1070 if( n >= serverlist_cachecount )
1074 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1075 // store the data the engine cares about (address and ping)
1076 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1077 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1078 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1080 ++serverlist_cachecount;
1083 // move on to next address in packet
1087 // begin or resume serverlist queries
1088 serverlist_querysleep = false;
1092 if (!strncmp(string, "ping", 4))
1094 if (developer.integer)
1095 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1096 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1099 if (!strncmp(string, "ack", 3))
1102 // we may not have liked the packet, but it was a command packet, so
1103 // we're done processing this packet now
1106 // netquake control packets, supported for compatibility only
1107 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1112 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1116 if (developer.integer)
1117 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1118 if (cls.connect_trying)
1120 lhnetaddress_t clientportaddress;
1121 clientportaddress = *peeraddress;
1124 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1127 LHNETADDRESS_SetPort(&clientportaddress, port);
1129 M_Update_Return_Reason("Accepted");
1130 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1134 if (developer.integer)
1135 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1136 cls.connect_trying = false;
1137 M_Update_Return_Reason(data);
1140 case CCREP_SERVER_INFO:
1141 if (developer.integer)
1142 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1143 if (cls.state != ca_dedicated)
1145 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1146 // string we just ignore it and keep the real address
1148 // serverlist only uses text addresses
1149 cname = UDP_AddrToString(readaddr);
1150 // search the cache for this server
1151 for (n = 0; n < hostCacheCount; n++)
1152 if (!strcmp(cname, serverlist[n].cname))
1155 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1158 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1159 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1160 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1161 serverlist[n].users = MSG_ReadByte();
1162 serverlist[n].maxusers = MSG_ReadByte();
1164 if (c != NET_PROTOCOL_VERSION)
1166 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1167 strcpy(serverlist[n].name, "*");
1168 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1170 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1174 case CCREP_PLAYER_INFO:
1175 // we got a CCREP_PLAYER_INFO??
1176 //if (developer.integer)
1177 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1179 case CCREP_RULE_INFO:
1180 // we got a CCREP_RULE_INFO??
1181 //if (developer.integer)
1182 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1188 // we may not have liked the packet, but it was a valid control
1189 // packet, so we're done processing this packet now
1193 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)
1194 CL_ParseServerMessage();
1198 void NetConn_QueryQueueFrame(void)
1204 static double querycounter = 0;
1206 if (serverlist_querysleep)
1209 // each time querycounter reaches 1.0 issue a query
1210 querycounter += host_realframetime * net_slist_queriespersecond.value;
1211 maxqueries = (int)querycounter;
1212 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1213 querycounter -= maxqueries;
1215 if( maxqueries == 0 ) {
1219 // scan serverlist and issue queries as needed
1220 serverlist_querysleep = true;
1222 timeouttime = realtime - net_slist_timeout.value;
1223 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1225 serverlist_entry_t *entry = &serverlist_cache[ index ];
1226 if( entry->query != SQS_QUERYING )
1231 serverlist_querysleep = false;
1232 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1237 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1239 lhnetaddress_t address;
1242 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1243 for (socket = 0; socket < cl_numsockets ; socket++) {
1244 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1247 entry->querytime = realtime;
1248 entry->querycounter++;
1250 // if not in the slist menu we should print the server to console
1251 if (serverlist_consoleoutput)
1252 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1258 entry->query = SQS_TIMEDOUT;
1263 void NetConn_ClientFrame(void)
1266 lhnetaddress_t peeraddress;
1268 NetConn_UpdateServerStuff();
1269 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1271 if (cls.connect_remainingtries == 0)
1272 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1273 cls.connect_nextsendtime = realtime + 1;
1274 cls.connect_remainingtries--;
1275 if (cls.connect_remainingtries <= -10)
1277 cls.connect_trying = false;
1278 M_Update_Return_Reason("Connect: Failed");
1281 // try challenge first (newer server)
1282 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1283 // then try netquake as a fallback (old server, or netquake)
1284 SZ_Clear(&net_message);
1285 // save space for the header, filled in later
1286 MSG_WriteLong(&net_message, 0);
1287 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1288 MSG_WriteString(&net_message, "QUAKE");
1289 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1290 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1291 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1292 SZ_Clear(&net_message);
1294 for (i = 0;i < cl_numsockets;i++) {
1295 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0) {
1296 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1299 NetConn_QueryQueueFrame();
1300 if (cls.netcon && realtime > cls.netcon->timeout)
1302 Con_Print("Connection timed out\n");
1304 Host_ShutdownServer (false);
1306 for (conn = netconn_list;conn;conn = conn->next)
1307 NetConn_ReSendMessage(conn);
1310 #define MAX_CHALLENGES 128
1313 lhnetaddress_t address;
1317 challenge[MAX_CHALLENGES];
1319 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1323 for (i = 0;i < bufferlength - 1;i++)
1327 c = rand () % (127 - 33) + 33;
1328 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1334 extern void SV_SendServerinfo (client_t *client);
1335 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1337 int i, n, ret, clientnum, responselength, best;
1341 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1345 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1347 // received a command string - strip off the packaging and put it
1348 // into our string buffer with NULL termination
1351 length = min(length, (int)sizeof(stringbuf) - 1);
1352 memcpy(stringbuf, data, length);
1353 stringbuf[length] = 0;
1356 if (developer.integer)
1358 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1359 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1360 Com_HexDumpToConsole(data, length);
1363 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1365 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1367 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1369 if (besttime > challenge[i].time)
1370 besttime = challenge[best = i].time;
1372 // if we did not find an exact match, choose the oldest and
1373 // update address and string
1374 if (i == MAX_CHALLENGES)
1377 challenge[i].address = *peeraddress;
1378 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1380 challenge[i].time = realtime;
1381 // send the challenge
1382 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1385 if (length > 8 && !memcmp(string, "connect\\", 8))
1389 if ((s = SearchInfostring(string, "challenge")))
1391 // validate the challenge
1392 for (i = 0;i < MAX_CHALLENGES;i++)
1393 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1395 if (i < MAX_CHALLENGES)
1397 // check engine protocol
1398 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1400 if (developer.integer)
1401 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1402 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1406 // see if this is a duplicate connection request
1407 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1408 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1410 if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1412 // client is still trying to connect,
1413 // so we send a duplicate reply
1414 if (developer.integer)
1415 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1416 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1419 else if (clientnum < svs.maxclients)
1421 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1423 // client crashed and is coming back, keep their stuff intact
1424 SV_SendServerinfo(client);
1425 //host_client = client;
1426 //SV_DropClient (true);
1433 // this is a new client, find a slot
1434 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1435 if (!client->active)
1437 if (clientnum < svs.maxclients)
1439 // prepare the client struct
1440 if ((conn = NetConn_Open(mysocket, peeraddress)))
1442 // allocated connection
1443 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1444 if (developer.integer)
1445 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1446 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1447 // now set up the client
1448 SV_ConnectClient(clientnum, conn);
1449 NetConn_Heartbeat(1);
1455 if (developer.integer)
1456 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1457 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1465 if (length >= 7 && !memcmp(string, "getinfo", 7))
1467 const char *challenge = NULL;
1468 // If there was a challenge in the getinfo message
1469 if (length > 8 && string[7] == ' ')
1470 challenge = string + 8;
1471 for (i = 0, n = 0;i < svs.maxclients;i++)
1472 if (svs.clients[i].active)
1474 responselength = dpsnprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1475 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1476 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1477 gamename, com_modname, svs.maxclients, n,
1478 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1479 // does it fit in the buffer?
1480 if (responselength >= 0)
1482 if (developer.integer)
1483 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1484 NetConn_WriteString(mysocket, response, peeraddress);
1489 if (!strncmp(string, "ping", 4))
1491 if (developer.integer)
1492 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1493 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1496 if (!strncmp(string, "ack", 3))
1499 // we may not have liked the packet, but it was a command packet, so
1500 // we're done processing this packet now
1503 // LordHavoc: disabled netquake control packet support in server
1507 // netquake control packets, supported for compatibility only
1508 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1513 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1517 //if (developer.integer)
1518 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1519 if (length >= (int)strlen("QUAKE") + 1 + 1)
1521 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1523 if (developer.integer)
1524 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1525 SZ_Clear(&net_message);
1526 // save space for the header, filled in later
1527 MSG_WriteLong(&net_message, 0);
1528 MSG_WriteByte(&net_message, CCREP_REJECT);
1529 MSG_WriteString(&net_message, "Incompatible version.\n");
1530 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1531 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1532 SZ_Clear(&net_message);
1536 // see if this is a duplicate connection request
1537 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1538 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1540 if (clientnum < svs.maxclients)
1542 // duplicate connection request
1543 if (realtime - client->connecttime < 2.0)
1545 // client is still trying to connect,
1546 // so we send a duplicate reply
1547 if (developer.integer)
1548 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT 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_ACCEPT);
1553 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1554 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1555 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1556 SZ_Clear(&net_message);
1559 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1561 SV_SendServerinfo(client);
1562 // the old client hasn't sent us anything
1563 // in quite a while, so kick off and let
1564 // the retry take care of it...
1565 //host_client = client;
1566 //SV_DropClient (true);
1572 // this is a new client, find a slot
1573 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1574 if (!client->active)
1576 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1578 // connect to the client
1579 // everything is allocated, just fill in the details
1580 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1581 if (developer.integer)
1582 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1583 // send back the info about the server connection
1584 SZ_Clear(&net_message);
1585 // save space for the header, filled in later
1586 MSG_WriteLong(&net_message, 0);
1587 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1588 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1589 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1590 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1591 SZ_Clear(&net_message);
1592 // now set up the client struct
1593 SV_ConnectClient(clientnum, conn);
1594 NetConn_Heartbeat(1);
1598 //if (developer.integer)
1599 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1600 // no room; try to let player know
1601 SZ_Clear(&net_message);
1602 // save space for the header, filled in later
1603 MSG_WriteLong(&net_message, 0);
1604 MSG_WriteByte(&net_message, CCREP_REJECT);
1605 MSG_WriteString(&net_message, "Server is full.\n");
1606 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1607 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1608 SZ_Clear(&net_message);
1615 case CCREQ_SERVER_INFO:
1616 if (developer.integer)
1617 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1618 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1620 if (developer.integer)
1621 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1622 SZ_Clear(&net_message);
1623 // save space for the header, filled in later
1624 MSG_WriteLong(&net_message, 0);
1625 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1626 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1627 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1628 MSG_WriteString(&net_message, hostname.string);
1629 MSG_WriteString(&net_message, sv.name);
1630 MSG_WriteByte(&net_message, net_activeconnections);
1631 MSG_WriteByte(&net_message, svs.maxclients);
1632 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1633 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1634 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1635 SZ_Clear(&net_message);
1638 case CCREQ_PLAYER_INFO:
1639 if (developer.integer)
1640 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1643 int playerNumber, activeNumber, clientNumber;
1646 playerNumber = MSG_ReadByte();
1648 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1649 if (client->active && ++activeNumber == playerNumber)
1651 if (clientNumber != svs.maxclients)
1653 SZ_Clear(&net_message);
1654 // save space for the header, filled in later
1655 MSG_WriteLong(&net_message, 0);
1656 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1657 MSG_WriteByte(&net_message, playerNumber);
1658 MSG_WriteString(&net_message, client->name);
1659 MSG_WriteLong(&net_message, client->colors);
1660 MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1661 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1662 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1663 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1664 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1665 SZ_Clear(&net_message);
1669 case CCREQ_RULE_INFO:
1670 if (developer.integer)
1671 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1677 // find the search start location
1678 prevCvarName = MSG_ReadString();
1679 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1681 // send the response
1682 SZ_Clear(&net_message);
1683 // save space for the header, filled in later
1684 MSG_WriteLong(&net_message, 0);
1685 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1688 MSG_WriteString(&net_message, var->name);
1689 MSG_WriteString(&net_message, var->string);
1691 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1692 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1693 SZ_Clear(&net_message);
1700 // we may not have liked the packet, but it was a valid control
1701 // packet, so we're done processing this packet now
1706 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1708 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1710 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1711 SV_ReadClientMessage();
1719 void NetConn_ServerFrame(void)
1722 lhnetaddress_t peeraddress;
1724 NetConn_UpdateServerStuff();
1725 for (i = 0;i < sv_numsockets;i++)
1726 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1727 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1728 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1730 // never timeout loopback connections
1731 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1733 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1734 SV_DropClient(false);
1737 for (conn = netconn_list;conn;conn = conn->next)
1738 NetConn_ReSendMessage(conn);
1741 void NetConn_QueryMasters(void)
1745 lhnetaddress_t masteraddress;
1746 lhnetaddress_t broadcastaddress;
1749 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1752 // 26000 is the default quake server port, servers on other ports will not
1754 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1755 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1757 for (i = 0;i < cl_numsockets;i++)
1761 // search LAN for Quake servers
1762 SZ_Clear(&net_message);
1763 // save space for the header, filled in later
1764 MSG_WriteLong(&net_message, 0);
1765 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1766 MSG_WriteString(&net_message, "QUAKE");
1767 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1768 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1769 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1770 SZ_Clear(&net_message);
1772 // search LAN for DarkPlaces servers
1773 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1775 // build the getservers message to send to the master servers
1776 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1779 for (masternum = 0;sv_masters[masternum].name;masternum++)
1781 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1784 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1789 if (!masterquerycount)
1791 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1792 M_Update_Return_Reason("No network");
1796 void NetConn_Heartbeat(int priority)
1798 lhnetaddress_t masteraddress;
1800 lhnetsocket_t *mysocket;
1802 // if it's a state change (client connected), limit next heartbeat to no
1803 // more than 30 sec in the future
1804 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1805 nextheartbeattime = realtime + 30.0;
1807 // limit heartbeatperiod to 30 to 270 second range,
1808 // lower limit is to avoid abusing master servers with excess traffic,
1809 // upper limit is to avoid timing out on the master server (which uses
1811 if (sv_heartbeatperiod.value < 30)
1812 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1813 if (sv_heartbeatperiod.value > 270)
1814 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1816 // make advertising optional and don't advertise singleplayer games, and
1817 // only send a heartbeat as often as the admin wants
1818 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1820 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1821 for (masternum = 0;sv_masters[masternum].name;masternum++)
1822 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1823 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1827 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1830 qbyte sent[MAX_SCOREBOARD];
1832 memset(sent, 0, sizeof(sent));
1834 // simultaneously wait for the first CanSendMessage and send the message,
1835 // then wait for a second CanSendMessage (verifying it was received), or
1836 // the client drops and is no longer counted
1837 // the loop aborts when either it runs out of clients to send to, or a
1839 blocktime += Sys_DoubleTime();
1843 NetConn_ClientFrame();
1844 NetConn_ServerFrame();
1845 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1847 if (host_client->netconnection)
1849 if (NetConn_CanSendMessage(host_client->netconnection))
1852 NetConn_SendReliableMessage(host_client->netconnection, data);
1855 if (!NetConn_CanSendMessage(host_client->netconnection))
1860 while (count && Sys_DoubleTime() < blocktime);
1864 static void Net_Heartbeat_f(void)
1867 NetConn_Heartbeat(2);
1869 Con_Print("No server running, can not heartbeat to master server.\n");
1872 void PrintStats(netconn_t *conn)
1874 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1877 void Net_Stats_f(void)
1880 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1881 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1882 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1883 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1884 Con_Printf("packetsSent = %i\n", packetsSent);
1885 Con_Printf("packetsReSent = %i\n", packetsReSent);
1886 Con_Printf("packetsReceived = %i\n", packetsReceived);
1887 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1888 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1889 Con_Print("connections =\n");
1890 for (conn = netconn_list;conn;conn = conn->next)
1894 void Net_Slist_f(void)
1896 ServerList_ResetMasks();
1897 serverlist_sortbyfield = SLIF_PING;
1898 serverlist_sortdescending = false;
1899 if (m_state != m_slist) {
1900 Con_Print("Sending requests to master servers\n");
1901 ServerList_QueryList();
1902 serverlist_consoleoutput = true;
1903 Con_Print("Listening for replies...\n");
1905 ServerList_QueryList();
1908 void NetConn_Init(void)
1911 lhnetaddress_t tempaddress;
1912 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
1913 Cmd_AddCommand("net_stats", Net_Stats_f);
1914 Cmd_AddCommand("net_slist", Net_Slist_f);
1915 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1916 Cvar_RegisterVariable(&net_slist_queriespersecond);
1917 Cvar_RegisterVariable(&net_slist_queriesperframe);
1918 Cvar_RegisterVariable(&net_slist_timeout);
1919 Cvar_RegisterVariable(&net_slist_maxtries);
1920 Cvar_RegisterVariable(&net_messagetimeout);
1921 Cvar_RegisterVariable(&net_messagerejointimeout);
1922 Cvar_RegisterVariable(&net_connecttimeout);
1923 Cvar_RegisterVariable(&cl_netlocalping);
1924 Cvar_RegisterVariable(&cl_netpacketloss);
1925 Cvar_RegisterVariable(&hostname);
1926 Cvar_RegisterVariable(&developer_networking);
1927 Cvar_RegisterVariable(&cl_netport);
1928 Cvar_RegisterVariable(&sv_netport);
1929 Cvar_RegisterVariable(&net_address);
1930 //Cvar_RegisterVariable(&net_address_ipv6);
1931 Cvar_RegisterVariable(&sv_public);
1932 Cvar_RegisterVariable(&sv_heartbeatperiod);
1933 for (i = 0;sv_masters[i].name;i++)
1934 Cvar_RegisterVariable(&sv_masters[i]);
1935 // 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.
1936 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1938 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1940 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1941 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1944 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1946 // 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
1947 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1949 i = atoi(com_argv[i + 1]);
1950 if (i >= 0 && i < 65536)
1952 Con_Printf("-port option used, setting port cvar to %i\n", i);
1953 Cvar_SetValueQuick(&sv_netport, i);
1956 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1960 net_message.data = net_message_buf;
1961 net_message.maxsize = sizeof(net_message_buf);
1962 net_message.cursize = 0;
1966 void NetConn_Shutdown(void)
1968 NetConn_CloseClientPorts();
1969 NetConn_CloseServerPorts();