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 // note this defaults on for dedicated servers, off for listen servers
29 cvar_t sv_public = {0, "sv_public", "0"};
30 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120"};
32 // FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat)
33 static cvar_t sv_masters [] =
35 {CVAR_SAVE, "sv_master1", ""},
36 {CVAR_SAVE, "sv_master2", ""},
37 {CVAR_SAVE, "sv_master3", ""},
38 {CVAR_SAVE, "sv_master4", ""},
39 {0, "sv_masterextra1", "ghdigital.com"}, //69.59.212.88
40 {0, "sv_masterextra2", "dpmaster.deathmask.net"}, //209.164.24.243
41 {0, "sv_masterextra3", "12.166.196.192"}, //blaze.mindphukd.org (doesn't resolve currently but works as an ip)
45 static double nextheartbeattime = 0;
47 sizebuf_t net_message;
48 static qbyte net_message_buf[NET_MAXMESSAGE];
50 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
51 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
52 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
53 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
54 cvar_t developer_networking = {0, "developer_networking", "0"};
56 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
57 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
58 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20"};
59 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4"};
60 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4"};
61 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3"};
63 /* statistic counters */
64 static int packetsSent = 0;
65 static int packetsReSent = 0;
66 static int packetsReceived = 0;
67 static int receivedDuplicateCount = 0;
68 static int droppedDatagrams = 0;
70 static int unreliableMessagesSent = 0;
71 static int unreliableMessagesReceived = 0;
72 static int reliableMessagesSent = 0;
73 static int reliableMessagesReceived = 0;
75 double masterquerytime = -1000;
76 int masterquerycount = 0;
77 int masterreplycount = 0;
78 int serverquerycount = 0;
79 int serverreplycount = 0;
81 // this is only false if there are still servers left to query
82 int serverlist_querysleep = true;
84 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
85 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
88 lhnetsocket_t *cl_sockets[16];
90 lhnetsocket_t *sv_sockets[16];
92 netconn_t *netconn_list = NULL;
93 mempool_t *netconn_mempool = NULL;
95 cvar_t cl_netport = {0, "cl_port", "0"};
96 cvar_t sv_netport = {0, "port", "26000"};
97 cvar_t net_address = {0, "net_address", "0.0.0.0"};
98 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
100 // ServerList interface
101 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
102 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
104 serverlist_infofield_t serverlist_sortbyfield;
105 qboolean serverlist_sortdescending;
107 int serverlist_viewcount = 0;
108 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
110 int serverlist_cachecount;
111 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
113 qboolean serverlist_consoleoutput;
115 // helper function to insert a value into the viewset
116 // spare entries will be removed
117 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
120 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
121 i = serverlist_viewcount++;
123 i = SERVERLIST_VIEWLISTSIZE - 1;
126 for( ; i > index ; i-- )
127 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
129 serverlist_viewlist[index] = entry;
132 // we suppose serverlist_viewcount to be valid, ie > 0
133 static void _ServerList_ViewList_Helper_Remove( int index )
135 serverlist_viewcount--;
136 for( ; index < serverlist_viewcount ; index++ )
137 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
140 // returns true if A should be inserted before B
141 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
143 int result = 0; // > 0 if for numbers A > B and for text if A < B
145 switch( serverlist_sortbyfield ) {
147 result = A->info.ping - B->info.ping;
149 case SLIF_MAXPLAYERS:
150 result = A->info.maxplayers - B->info.maxplayers;
152 case SLIF_NUMPLAYERS:
153 result = A->info.numplayers - B->info.numplayers;
156 result = A->info.protocol - B->info.protocol;
159 result = strcmp( B->info.cname, A->info.cname );
162 result = strcmp( B->info.game, A->info.game );
165 result = strcmp( B->info.map, A->info.map );
168 result = strcmp( B->info.mod, A->info.mod );
171 result = strcmp( B->info.name, A->info.name );
174 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
178 if( serverlist_sortdescending )
183 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
185 // This should actually be done with some intermediate and end-of-function return
197 case SLMO_GREATEREQUAL:
199 case SLMO_NOTCONTAIN:
202 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
207 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
209 char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
210 strcpy( bufferA, A );
213 strcpy( bufferB, B );
216 // Same here, also using an intermediate & final return would be more appropriate
220 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
221 case SLMO_NOTCONTAIN:
222 return !*bufferB || !strstr( bufferA, bufferB );
224 return strcmp( bufferA, bufferB ) < 0;
226 return strcmp( bufferA, bufferB ) <= 0;
228 return strcmp( bufferA, bufferB ) == 0;
230 return strcmp( bufferA, bufferB ) > 0;
232 return strcmp( bufferA, bufferB ) != 0;
233 case SLMO_GREATEREQUAL:
234 return strcmp( bufferA, bufferB ) >= 0;
236 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
241 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
243 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
245 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
247 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
249 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
251 if( *mask->info.cname
252 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
255 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
258 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
261 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
264 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
269 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
273 // FIXME: change this to be more readable (...)
274 // now check whether it passes through the masks
275 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
276 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
279 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
280 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
282 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
285 if( !serverlist_viewcount ) {
286 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
289 // ok, insert it, we just need to find out where exactly:
292 // check whether to insert it as new first item
293 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
294 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
296 } // check whether to insert it as new last item
297 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
298 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
302 end = serverlist_viewcount - 1;
303 while( end > start + 1 )
305 mid = (start + end) / 2;
306 // test the item that lies in the middle between start and end
307 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
308 // the item has to be in the upper half
311 // the item has to be in the lower half
314 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
317 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
320 for( i = 0; i < serverlist_viewcount; i++ )
322 if (serverlist_viewlist[i] == entry)
324 _ServerList_ViewList_Helper_Remove(i);
330 void ServerList_RebuildViewList(void)
334 serverlist_viewcount = 0;
335 for( i = 0 ; i < serverlist_cachecount ; i++ )
336 if( serverlist_cache[i].query == SQS_QUERIED )
337 ServerList_ViewList_Insert( &serverlist_cache[i] );
340 void ServerList_ResetMasks(void)
342 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
343 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
347 static void _ServerList_Test(void)
350 for( i = 0 ; i < 1024 ; i++ ) {
351 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
352 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
353 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, 128, "Black's ServerList Test %i", i );
354 serverlist_cache[serverlist_cachecount].finished = true;
355 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
356 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
357 serverlist_cachecount++;
362 void ServerList_QueryList(void)
364 masterquerytime = realtime;
365 masterquerycount = 0;
366 masterreplycount = 0;
367 serverquerycount = 0;
368 serverreplycount = 0;
369 serverlist_cachecount = 0;
370 serverlist_viewcount = 0;
371 serverlist_consoleoutput = false;
373 //_ServerList_Test();
375 NetConn_QueryMasters();
380 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
382 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
386 if (cl_netpacketloss.integer)
387 for (i = 0;i < cl_numsockets;i++)
388 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
390 if (developer_networking.integer)
392 char addressstring[128], addressstring2[128];
393 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
396 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
397 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
398 Com_HexDumpToConsole(data, length);
401 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
406 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
410 if (cl_netpacketloss.integer)
411 for (i = 0;i < cl_numsockets;i++)
412 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
414 ret = LHNET_Write(mysocket, data, length, peeraddress);
415 if (developer_networking.integer)
417 char addressstring[128], addressstring2[128];
418 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
419 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
420 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
421 Com_HexDumpToConsole(data, length);
426 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
428 // note this does not include the trailing NULL because we add that in the parser
429 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
432 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
434 unsigned int packetLen;
435 unsigned int dataLen;
437 unsigned int *header;
440 if (data->cursize == 0)
441 Sys_Error("Datagram_SendMessage: zero length message\n");
443 if (data->cursize > (int)sizeof(conn->sendMessage))
444 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
446 if (conn->canSend == false)
447 Sys_Error("SendMessage: called with canSend == false\n");
450 memcpy(conn->sendMessage, data->data, data->cursize);
451 conn->sendMessageLength = data->cursize;
453 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
455 dataLen = conn->sendMessageLength;
460 dataLen = MAX_PACKETFRAGMENT;
464 packetLen = NET_HEADERSIZE + dataLen;
466 header = (void *)sendbuffer;
467 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
468 header[1] = BigLong(conn->sendSequence);
469 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
471 conn->sendSequence++;
472 conn->canSend = false;
474 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
477 conn->lastSendTime = realtime;
479 reliableMessagesSent++;
483 static void NetConn_SendMessageNext(netconn_t *conn)
485 unsigned int packetLen;
486 unsigned int dataLen;
488 unsigned int *header;
490 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
492 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
494 dataLen = conn->sendMessageLength;
499 dataLen = MAX_PACKETFRAGMENT;
503 packetLen = NET_HEADERSIZE + dataLen;
505 header = (void *)sendbuffer;
506 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
507 header[1] = BigLong(conn->sendSequence);
508 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
510 conn->sendSequence++;
511 conn->sendNext = false;
513 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
516 conn->lastSendTime = realtime;
521 static void NetConn_ReSendMessage(netconn_t *conn)
523 unsigned int packetLen;
524 unsigned int dataLen;
526 unsigned int *header;
528 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
530 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
532 dataLen = conn->sendMessageLength;
537 dataLen = MAX_PACKETFRAGMENT;
541 packetLen = NET_HEADERSIZE + dataLen;
543 header = (void *)sendbuffer;
544 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
545 header[1] = BigLong(conn->sendSequence - 1);
546 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
548 conn->sendNext = false;
550 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
553 conn->lastSendTime = realtime;
558 qboolean NetConn_CanSendMessage(netconn_t *conn)
560 return conn->canSend;
563 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
568 packetLen = NET_HEADERSIZE + data->cursize;
571 if (data->cursize == 0)
572 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
574 if (packetLen > (int)sizeof(sendbuffer))
575 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
578 header = (void *)sendbuffer;
579 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
580 header[1] = BigLong(conn->unreliableSendSequence);
581 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
583 conn->unreliableSendSequence++;
585 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
589 unreliableMessagesSent++;
593 void NetConn_CloseClientPorts(void)
595 for (;cl_numsockets > 0;cl_numsockets--)
596 if (cl_sockets[cl_numsockets - 1])
597 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
600 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
602 lhnetaddress_t address;
604 char addressstring2[1024];
605 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
607 if ((s = LHNET_OpenSocket_Connectionless(&address)))
609 cl_sockets[cl_numsockets++] = s;
610 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
611 Con_Printf("Client opened a socket on address %s\n", addressstring2);
615 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
616 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
620 Con_Printf("Client unable to parse address %s\n", addressstring);
623 void NetConn_OpenClientPorts(void)
626 NetConn_CloseClientPorts();
627 port = bound(0, cl_netport.integer, 65535);
628 if (cl_netport.integer != port)
629 Cvar_SetValueQuick(&cl_netport, port);
630 Con_Printf("Client using port %i\n", port);
631 NetConn_OpenClientPort("local:2", 0);
632 NetConn_OpenClientPort(net_address.string, port);
633 //NetConn_OpenClientPort(net_address_ipv6.string, port);
636 void NetConn_CloseServerPorts(void)
638 for (;sv_numsockets > 0;sv_numsockets--)
639 if (sv_sockets[sv_numsockets - 1])
640 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
643 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
645 lhnetaddress_t address;
647 char addressstring2[1024];
648 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
650 if ((s = LHNET_OpenSocket_Connectionless(&address)))
652 sv_sockets[sv_numsockets++] = s;
653 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
654 Con_Printf("Server listening on address %s\n", addressstring2);
658 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
659 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
663 Con_Printf("Server unable to parse address %s\n", addressstring);
666 void NetConn_OpenServerPorts(int opennetports)
669 NetConn_CloseServerPorts();
670 port = bound(0, sv_netport.integer, 65535);
673 Con_Printf("Server using port %i\n", port);
674 if (sv_netport.integer != port)
675 Cvar_SetValueQuick(&sv_netport, port);
676 if (cls.state != ca_dedicated)
677 NetConn_OpenServerPort("local:1", 0);
680 NetConn_OpenServerPort(net_address.string, port);
681 //NetConn_OpenServerPort(net_address_ipv6.string, port);
683 if (sv_numsockets == 0)
684 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
687 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
689 int i, a = LHNETADDRESS_GetAddressType(address);
690 for (i = 0;i < cl_numsockets;i++)
691 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
692 return cl_sockets[i];
696 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
698 int i, a = LHNETADDRESS_GetAddressType(address);
699 for (i = 0;i < sv_numsockets;i++)
700 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
701 return sv_sockets[i];
705 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
708 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
709 conn->mysocket = mysocket;
710 conn->peeraddress = *peeraddress;
711 conn->canSend = true;
712 conn->lastMessageTime = realtime;
713 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
714 // reduce effectiveness of connection request floods
715 conn->timeout = realtime + net_connecttimeout.value;
716 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
717 conn->next = netconn_list;
722 void NetConn_Close(netconn_t *conn)
725 // remove connection from list
726 if (conn == netconn_list)
727 netconn_list = conn->next;
730 for (c = netconn_list;c;c = c->next)
734 c->next = conn->next;
738 // not found in list, we'll avoid crashing here...
746 static int clientport = -1;
747 static int clientport2 = -1;
748 static int hostport = -1;
749 static void NetConn_UpdateServerStuff(void)
751 if (cls.state != ca_dedicated)
753 if (clientport2 != cl_netport.integer)
755 clientport2 = cl_netport.integer;
756 if (cls.state == ca_connected)
757 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
759 if (cls.state == ca_disconnected && clientport != clientport2)
761 clientport = clientport2;
762 NetConn_CloseClientPorts();
764 if (cl_numsockets == 0)
765 NetConn_OpenClientPorts();
768 if (hostport != sv_netport.integer)
770 hostport = sv_netport.integer;
772 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
776 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
780 unsigned int sequence;
785 qlength = (unsigned int)BigLong(((int *)data)[0]);
786 flags = qlength & ~NETFLAG_LENGTH_MASK;
787 qlength &= NETFLAG_LENGTH_MASK;
788 // control packets were already handled
789 if (!(flags & NETFLAG_CTL) && qlength == length)
791 sequence = BigLong(((int *)data)[1]);
795 if (flags & NETFLAG_UNRELIABLE)
797 if (sequence >= conn->unreliableReceiveSequence)
799 if (sequence > conn->unreliableReceiveSequence)
801 count = sequence - conn->unreliableReceiveSequence;
802 droppedDatagrams += count;
803 Con_DPrintf("Dropped %u datagram(s)\n", count);
805 conn->unreliableReceiveSequence = sequence + 1;
806 conn->lastMessageTime = realtime;
807 conn->timeout = realtime + net_messagetimeout.value;
808 unreliableMessagesReceived++;
811 SZ_Clear(&net_message);
812 SZ_Write(&net_message, data, length);
818 Con_DPrint("Got a stale datagram\n");
821 else if (flags & NETFLAG_ACK)
823 if (sequence == (conn->sendSequence - 1))
825 if (sequence == conn->ackSequence)
828 if (conn->ackSequence != conn->sendSequence)
829 Con_DPrint("ack sequencing error\n");
830 conn->lastMessageTime = realtime;
831 conn->timeout = realtime + net_messagetimeout.value;
832 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
833 if (conn->sendMessageLength > 0)
835 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
836 conn->sendNext = true;
837 NetConn_SendMessageNext(conn);
841 conn->sendMessageLength = 0;
842 conn->canSend = true;
846 Con_DPrint("Duplicate ACK received\n");
849 Con_DPrint("Stale ACK received\n");
852 else if (flags & NETFLAG_DATA)
854 unsigned int temppacket[2];
855 temppacket[0] = BigLong(8 | NETFLAG_ACK);
856 temppacket[1] = BigLong(sequence);
857 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
858 if (sequence == conn->receiveSequence)
860 conn->lastMessageTime = realtime;
861 conn->timeout = realtime + net_messagetimeout.value;
862 conn->receiveSequence++;
863 if( conn->receiveMessageLength + length <= sizeof( conn->receiveMessage ) ) {
864 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
865 conn->receiveMessageLength += length;
867 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
868 "Dropping the message!\n", sequence );
869 conn->receiveMessageLength = 0;
872 if (flags & NETFLAG_EOM)
874 reliableMessagesReceived++;
875 length = conn->receiveMessageLength;
876 conn->receiveMessageLength = 0;
879 SZ_Clear(&net_message);
880 SZ_Write(&net_message, conn->receiveMessage, length);
887 receivedDuplicateCount++;
895 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
897 cls.connect_trying = false;
898 M_Update_Return_Reason("");
899 // the connection request succeeded, stop current connection and set up a new connection
901 // if we're connecting to a remote server, shut down any local server
902 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
903 Host_ShutdownServer (false);
904 // allocate a net connection to keep track of things
905 cls.netcon = NetConn_Open(mysocket, peeraddress);
906 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
909 cls.demonum = -1; // not in the demo loop now
910 cls.state = ca_connected;
911 cls.signon = 0; // need all the signon messages before playing
914 int NetConn_IsLocalGame(void)
916 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
921 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
925 char *string, addressstring2[128], cname[128], ipstring[32];
926 char stringbuf[16384];
928 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
930 // received a command string - strip off the packaging and put it
931 // into our string buffer with NULL termination
934 length = min(length, (int)sizeof(stringbuf) - 1);
935 memcpy(stringbuf, data, length);
936 stringbuf[length] = 0;
939 if (developer.integer)
941 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
942 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
943 Com_HexDumpToConsole(data, length);
946 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
948 char protocolnames[1400];
949 Protocol_Names(protocolnames, sizeof(protocolnames));
950 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
951 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
952 M_Update_Return_Reason("Got challenge response");
953 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
956 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
958 M_Update_Return_Reason("Accepted");
959 NetConn_ConnectionEstablished(mysocket, peeraddress);
962 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
964 char rejectreason[32];
965 cls.connect_trying = false;
967 length = max(length - 7, (int)sizeof(rejectreason) - 1);
968 memcpy(rejectreason, string, length);
969 rejectreason[length] = 0;
970 M_Update_Return_Reason(rejectreason);
973 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
975 serverlist_info_t *info;
980 // serverlist only uses text addresses
981 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
982 // search the cache for this server and update it
983 for( n = 0; n < serverlist_cachecount; n++ )
984 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
986 if( n == serverlist_cachecount ) {
987 // LAN search doesnt require an answer from the master server so we wont
988 // know the ping nor will it be initialized already...
991 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
994 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
995 // store the data the engine cares about (address and ping)
996 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
997 serverlist_cache[serverlist_cachecount].info.ping = 100000;
998 serverlist_cache[serverlist_cachecount].querytime = realtime;
999 // if not in the slist menu we should print the server to console
1000 if (serverlist_consoleoutput) {
1001 Con_Printf("querying %s\n", ipstring);
1004 ++serverlist_cachecount;
1007 info = &serverlist_cache[n].info;
1008 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1009 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1010 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1011 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1012 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1013 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1014 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1016 if (info->ping == 100000)
1019 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1020 pingtime = bound(0, pingtime, 9999);
1022 info->ping = pingtime;
1024 // legacy/old stuff move it to the menu ASAP
1026 // build description strings for the things users care about
1027 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);
1028 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);
1029 // if ping is especially high, display it as such
1030 if (pingtime >= 300)
1032 // orange numbers (lower block)
1033 for (i = 0;i < 5;i++)
1034 if (serverlist_cache[n].line1[i] != ' ')
1035 serverlist_cache[n].line1[i] += 128;
1037 else if (pingtime >= 200)
1039 // yellow numbers (in upper block)
1040 for (i = 0;i < 5;i++)
1041 if (serverlist_cache[n].line1[i] != ' ')
1042 serverlist_cache[n].line1[i] -= 30;
1044 if( serverlist_cache[n].query == SQS_QUERIED ) {
1045 ServerList_ViewList_Remove( &serverlist_cache[n] );
1047 // if not in the slist menu we should print the server to console (if wanted)
1048 else if( serverlist_consoleoutput )
1049 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1050 // and finally, update the view set
1051 ServerList_ViewList_Insert( &serverlist_cache[n] );
1052 serverlist_cache[n].query = SQS_QUERIED;
1056 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1058 // Extract the IP addresses
1062 if (serverlist_consoleoutput)
1063 Con_Print("received server list...\n");
1064 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1068 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1069 if (developer.integer)
1070 Con_Printf("Requesting info from server %s\n", ipstring);
1071 // ignore the rest of the message if the serverlist is full
1072 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1074 // also ignore it if we have already queried it (other master server response)
1075 for( n = 0 ; n < serverlist_cachecount ; n++ )
1076 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1078 if( n >= serverlist_cachecount )
1082 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1083 // store the data the engine cares about (address and ping)
1084 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1085 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1086 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1088 ++serverlist_cachecount;
1091 // move on to next address in packet
1095 // begin or resume serverlist queries
1096 serverlist_querysleep = false;
1100 if (!strncmp(string, "ping", 4))
1102 if (developer.integer)
1103 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1104 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1107 if (!strncmp(string, "ack", 3))
1110 // we may not have liked the packet, but it was a command packet, so
1111 // we're done processing this packet now
1114 // netquake control packets, supported for compatibility only
1115 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1120 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1124 if (developer.integer)
1125 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1126 if (cls.connect_trying)
1128 lhnetaddress_t clientportaddress;
1129 clientportaddress = *peeraddress;
1132 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1135 LHNETADDRESS_SetPort(&clientportaddress, port);
1137 M_Update_Return_Reason("Accepted");
1138 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1142 if (developer.integer)
1143 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1144 cls.connect_trying = false;
1145 M_Update_Return_Reason(data);
1148 case CCREP_SERVER_INFO:
1149 if (developer.integer)
1150 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1151 if (cls.state != ca_dedicated)
1153 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1154 // string we just ignore it and keep the real address
1156 // serverlist only uses text addresses
1157 cname = UDP_AddrToString(readaddr);
1158 // search the cache for this server
1159 for (n = 0; n < hostCacheCount; n++)
1160 if (!strcmp(cname, serverlist[n].cname))
1163 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1166 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1167 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1168 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1169 serverlist[n].users = MSG_ReadByte();
1170 serverlist[n].maxusers = MSG_ReadByte();
1172 if (c != NET_PROTOCOL_VERSION)
1174 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1175 strcpy(serverlist[n].name, "*");
1176 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1178 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1182 case CCREP_PLAYER_INFO:
1183 // we got a CCREP_PLAYER_INFO??
1184 //if (developer.integer)
1185 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1187 case CCREP_RULE_INFO:
1188 // we got a CCREP_RULE_INFO??
1189 //if (developer.integer)
1190 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1196 // we may not have liked the packet, but it was a valid control
1197 // packet, so we're done processing this packet now
1201 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)
1202 CL_ParseServerMessage();
1206 void NetConn_QueryQueueFrame(void)
1212 static double querycounter = 0;
1214 if (serverlist_querysleep)
1217 // each time querycounter reaches 1.0 issue a query
1218 querycounter += host_realframetime * net_slist_queriespersecond.value;
1219 maxqueries = (int)querycounter;
1220 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1221 querycounter -= maxqueries;
1223 if( maxqueries == 0 ) {
1227 // scan serverlist and issue queries as needed
1228 serverlist_querysleep = true;
1230 timeouttime = realtime - net_slist_timeout.value;
1231 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1233 serverlist_entry_t *entry = &serverlist_cache[ index ];
1234 if( entry->query != SQS_QUERYING )
1239 serverlist_querysleep = false;
1240 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1245 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1247 lhnetaddress_t address;
1250 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1251 for (socket = 0; socket < cl_numsockets ; socket++) {
1252 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1255 entry->querytime = realtime;
1256 entry->querycounter++;
1258 // if not in the slist menu we should print the server to console
1259 if (serverlist_consoleoutput)
1260 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1266 entry->query = SQS_TIMEDOUT;
1271 void NetConn_ClientFrame(void)
1274 lhnetaddress_t peeraddress;
1276 NetConn_UpdateServerStuff();
1277 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1279 if (cls.connect_remainingtries == 0)
1280 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1281 cls.connect_nextsendtime = realtime + 1;
1282 cls.connect_remainingtries--;
1283 if (cls.connect_remainingtries <= -10)
1285 cls.connect_trying = false;
1286 M_Update_Return_Reason("Connect: Failed");
1289 // try challenge first (newer server)
1290 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1291 // then try netquake as a fallback (old server, or netquake)
1292 SZ_Clear(&net_message);
1293 // save space for the header, filled in later
1294 MSG_WriteLong(&net_message, 0);
1295 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1296 MSG_WriteString(&net_message, "QUAKE");
1297 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1298 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1299 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1300 SZ_Clear(&net_message);
1302 for (i = 0;i < cl_numsockets;i++) {
1303 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0) {
1304 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1307 NetConn_QueryQueueFrame();
1308 if (cls.netcon && realtime > cls.netcon->timeout)
1310 Con_Print("Connection timed out\n");
1312 Host_ShutdownServer (false);
1314 for (conn = netconn_list;conn;conn = conn->next)
1315 NetConn_ReSendMessage(conn);
1318 #define MAX_CHALLENGES 128
1321 lhnetaddress_t address;
1325 challenge[MAX_CHALLENGES];
1327 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1331 for (i = 0;i < bufferlength - 1;i++)
1335 c = rand () % (127 - 33) + 33;
1336 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1342 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1344 unsigned int nb_clients = 0, i;
1347 // How many clients are there?
1348 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1349 if (svs.clients[i].active)
1352 // TODO: we should add more information for the full status string
1353 length = dpsnprintf(out_msg, out_size,
1354 "\377\377\377\377%s\x0A"
1355 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1356 "\\clients\\%d\\mapname\\%s\\hostname\\%s""\\protocol\\%d"
1359 fullstatus ? "statusResponse" : "infoResponse",
1360 gamename, com_modname, svs.maxclients,
1361 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1362 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1363 fullstatus ? "\n" : "");
1365 // Make sure it fits in the buffer
1374 ptr = out_msg + length;
1375 left = out_size - length;
1377 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1379 client_t *cl = &svs.clients[i];
1382 int nameind, cleanind;
1384 char cleanname [sizeof(cl->name)];
1386 // Remove all characters '"' and '\' in the player name
1391 curchar = cl->name[nameind++];
1392 if (curchar != '"' && curchar != '\\')
1394 cleanname[cleanind++] = curchar;
1395 if (cleanind == sizeof(cleanname) - 1)
1398 } while (curchar != '\0');
1400 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1402 (int)(cl->ping * 1000.0f),
1415 extern void SV_SendServerinfo (client_t *client);
1416 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1418 int i, ret, clientnum, best;
1422 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1426 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1428 // received a command string - strip off the packaging and put it
1429 // into our string buffer with NULL termination
1432 length = min(length, (int)sizeof(stringbuf) - 1);
1433 memcpy(stringbuf, data, length);
1434 stringbuf[length] = 0;
1437 if (developer.integer)
1439 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1440 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1441 Com_HexDumpToConsole(data, length);
1444 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1446 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1448 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1450 if (besttime > challenge[i].time)
1451 besttime = challenge[best = i].time;
1453 // if we did not find an exact match, choose the oldest and
1454 // update address and string
1455 if (i == MAX_CHALLENGES)
1458 challenge[i].address = *peeraddress;
1459 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1461 challenge[i].time = realtime;
1462 // send the challenge
1463 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1466 if (length > 8 && !memcmp(string, "connect\\", 8))
1470 if ((s = SearchInfostring(string, "challenge")))
1472 // validate the challenge
1473 for (i = 0;i < MAX_CHALLENGES;i++)
1474 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1476 if (i < MAX_CHALLENGES)
1478 // check engine protocol
1479 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1481 if (developer.integer)
1482 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1483 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1487 // see if this is a duplicate connection request
1488 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1489 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1491 if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1493 // client is still trying to connect,
1494 // so we send a duplicate reply
1495 if (developer.integer)
1496 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1497 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1500 else if (clientnum < svs.maxclients)
1502 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1504 // client crashed and is coming back, keep their stuff intact
1505 SV_SendServerinfo(client);
1506 //host_client = client;
1507 //SV_DropClient (true);
1514 // this is a new client, find a slot
1515 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1516 if (!client->active)
1518 if (clientnum < svs.maxclients)
1520 // prepare the client struct
1521 if ((conn = NetConn_Open(mysocket, peeraddress)))
1523 // allocated connection
1524 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1525 if (developer.integer)
1526 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1527 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1528 // now set up the client
1529 SV_ConnectClient(clientnum, conn);
1530 NetConn_Heartbeat(1);
1536 if (developer.integer)
1537 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1538 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1546 if (length >= 7 && !memcmp(string, "getinfo", 7))
1548 const char *challenge = NULL;
1550 // If there was a challenge in the getinfo message
1551 if (length > 8 && string[7] == ' ')
1552 challenge = string + 8;
1554 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1556 if (developer.integer)
1557 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1558 NetConn_WriteString(mysocket, response, peeraddress);
1562 if (length >= 9 && !memcmp(string, "getstatus", 9))
1564 const char *challenge = NULL;
1566 // If there was a challenge in the getinfo message
1567 if (length > 10 && string[9] == ' ')
1568 challenge = string + 10;
1570 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1572 if (developer.integer)
1573 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1574 NetConn_WriteString(mysocket, response, peeraddress);
1579 if (!strncmp(string, "ping", 4))
1581 if (developer.integer)
1582 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1583 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1586 if (!strncmp(string, "ack", 3))
1589 // we may not have liked the packet, but it was a command packet, so
1590 // we're done processing this packet now
1593 // LordHavoc: disabled netquake control packet support in server
1597 // netquake control packets, supported for compatibility only
1598 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1603 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1607 //if (developer.integer)
1608 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1609 if (length >= (int)strlen("QUAKE") + 1 + 1)
1611 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1613 if (developer.integer)
1614 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1615 SZ_Clear(&net_message);
1616 // save space for the header, filled in later
1617 MSG_WriteLong(&net_message, 0);
1618 MSG_WriteByte(&net_message, CCREP_REJECT);
1619 MSG_WriteString(&net_message, "Incompatible version.\n");
1620 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1621 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1622 SZ_Clear(&net_message);
1626 // see if this is a duplicate connection request
1627 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1628 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1630 if (clientnum < svs.maxclients)
1632 // duplicate connection request
1633 if (realtime - client->connecttime < 2.0)
1635 // client is still trying to connect,
1636 // so we send a duplicate reply
1637 if (developer.integer)
1638 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1639 SZ_Clear(&net_message);
1640 // save space for the header, filled in later
1641 MSG_WriteLong(&net_message, 0);
1642 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1643 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1644 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1645 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1646 SZ_Clear(&net_message);
1649 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1651 SV_SendServerinfo(client);
1652 // the old client hasn't sent us anything
1653 // in quite a while, so kick off and let
1654 // the retry take care of it...
1655 //host_client = client;
1656 //SV_DropClient (true);
1662 // this is a new client, find a slot
1663 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1664 if (!client->active)
1666 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1668 // connect to the client
1669 // everything is allocated, just fill in the details
1670 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1671 if (developer.integer)
1672 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1673 // send back the info about the server connection
1674 SZ_Clear(&net_message);
1675 // save space for the header, filled in later
1676 MSG_WriteLong(&net_message, 0);
1677 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1678 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1679 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1680 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1681 SZ_Clear(&net_message);
1682 // now set up the client struct
1683 SV_ConnectClient(clientnum, conn);
1684 NetConn_Heartbeat(1);
1688 //if (developer.integer)
1689 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1690 // no room; try to let player know
1691 SZ_Clear(&net_message);
1692 // save space for the header, filled in later
1693 MSG_WriteLong(&net_message, 0);
1694 MSG_WriteByte(&net_message, CCREP_REJECT);
1695 MSG_WriteString(&net_message, "Server is full.\n");
1696 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1697 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1698 SZ_Clear(&net_message);
1705 case CCREQ_SERVER_INFO:
1706 if (developer.integer)
1707 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1708 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1710 if (developer.integer)
1711 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1712 SZ_Clear(&net_message);
1713 // save space for the header, filled in later
1714 MSG_WriteLong(&net_message, 0);
1715 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1716 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1717 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1718 MSG_WriteString(&net_message, hostname.string);
1719 MSG_WriteString(&net_message, sv.name);
1720 MSG_WriteByte(&net_message, net_activeconnections);
1721 MSG_WriteByte(&net_message, svs.maxclients);
1722 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1723 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1724 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1725 SZ_Clear(&net_message);
1728 case CCREQ_PLAYER_INFO:
1729 if (developer.integer)
1730 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1733 int playerNumber, activeNumber, clientNumber;
1736 playerNumber = MSG_ReadByte();
1738 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1739 if (client->active && ++activeNumber == playerNumber)
1741 if (clientNumber != svs.maxclients)
1743 SZ_Clear(&net_message);
1744 // save space for the header, filled in later
1745 MSG_WriteLong(&net_message, 0);
1746 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1747 MSG_WriteByte(&net_message, playerNumber);
1748 MSG_WriteString(&net_message, client->name);
1749 MSG_WriteLong(&net_message, client->colors);
1750 MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1751 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1752 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1753 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1754 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1755 SZ_Clear(&net_message);
1759 case CCREQ_RULE_INFO:
1760 if (developer.integer)
1761 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1767 // find the search start location
1768 prevCvarName = MSG_ReadString();
1769 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1771 // send the response
1772 SZ_Clear(&net_message);
1773 // save space for the header, filled in later
1774 MSG_WriteLong(&net_message, 0);
1775 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1778 MSG_WriteString(&net_message, var->name);
1779 MSG_WriteString(&net_message, var->string);
1781 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1782 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1783 SZ_Clear(&net_message);
1790 // we may not have liked the packet, but it was a valid control
1791 // packet, so we're done processing this packet now
1796 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1798 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1800 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1801 SV_ReadClientMessage();
1809 void NetConn_ServerFrame(void)
1812 lhnetaddress_t peeraddress;
1814 NetConn_UpdateServerStuff();
1815 for (i = 0;i < sv_numsockets;i++)
1816 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1817 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1818 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1820 // never timeout loopback connections
1821 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1823 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1824 SV_DropClient(false);
1827 for (conn = netconn_list;conn;conn = conn->next)
1828 NetConn_ReSendMessage(conn);
1831 void NetConn_QueryMasters(void)
1835 lhnetaddress_t masteraddress;
1836 lhnetaddress_t broadcastaddress;
1839 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1842 // 26000 is the default quake server port, servers on other ports will not
1844 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1845 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1847 for (i = 0;i < cl_numsockets;i++)
1851 // search LAN for Quake servers
1852 SZ_Clear(&net_message);
1853 // save space for the header, filled in later
1854 MSG_WriteLong(&net_message, 0);
1855 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1856 MSG_WriteString(&net_message, "QUAKE");
1857 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1858 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1859 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1860 SZ_Clear(&net_message);
1862 // search LAN for DarkPlaces servers
1863 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1865 // build the getservers message to send to the master servers
1866 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1869 for (masternum = 0;sv_masters[masternum].name;masternum++)
1871 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1874 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1879 if (!masterquerycount)
1881 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1882 M_Update_Return_Reason("No network");
1886 void NetConn_Heartbeat(int priority)
1888 lhnetaddress_t masteraddress;
1890 lhnetsocket_t *mysocket;
1892 // if it's a state change (client connected), limit next heartbeat to no
1893 // more than 30 sec in the future
1894 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1895 nextheartbeattime = realtime + 30.0;
1897 // limit heartbeatperiod to 30 to 270 second range,
1898 // lower limit is to avoid abusing master servers with excess traffic,
1899 // upper limit is to avoid timing out on the master server (which uses
1901 if (sv_heartbeatperiod.value < 30)
1902 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1903 if (sv_heartbeatperiod.value > 270)
1904 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1906 // make advertising optional and don't advertise singleplayer games, and
1907 // only send a heartbeat as often as the admin wants
1908 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1910 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1911 for (masternum = 0;sv_masters[masternum].name;masternum++)
1912 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1913 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1917 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1920 qbyte sent[MAX_SCOREBOARD];
1922 memset(sent, 0, sizeof(sent));
1924 // simultaneously wait for the first CanSendMessage and send the message,
1925 // then wait for a second CanSendMessage (verifying it was received), or
1926 // the client drops and is no longer counted
1927 // the loop aborts when either it runs out of clients to send to, or a
1929 blocktime += Sys_DoubleTime();
1933 NetConn_ClientFrame();
1934 NetConn_ServerFrame();
1935 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1937 if (host_client->netconnection)
1939 if (NetConn_CanSendMessage(host_client->netconnection))
1942 NetConn_SendReliableMessage(host_client->netconnection, data);
1945 if (!NetConn_CanSendMessage(host_client->netconnection))
1950 while (count && Sys_DoubleTime() < blocktime);
1954 static void Net_Heartbeat_f(void)
1957 NetConn_Heartbeat(2);
1959 Con_Print("No server running, can not heartbeat to master server.\n");
1962 void PrintStats(netconn_t *conn)
1964 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1967 void Net_Stats_f(void)
1970 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1971 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1972 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1973 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1974 Con_Printf("packetsSent = %i\n", packetsSent);
1975 Con_Printf("packetsReSent = %i\n", packetsReSent);
1976 Con_Printf("packetsReceived = %i\n", packetsReceived);
1977 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1978 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1979 Con_Print("connections =\n");
1980 for (conn = netconn_list;conn;conn = conn->next)
1984 void Net_Slist_f(void)
1986 ServerList_ResetMasks();
1987 serverlist_sortbyfield = SLIF_PING;
1988 serverlist_sortdescending = false;
1989 if (m_state != m_slist) {
1990 Con_Print("Sending requests to master servers\n");
1991 ServerList_QueryList();
1992 serverlist_consoleoutput = true;
1993 Con_Print("Listening for replies...\n");
1995 ServerList_QueryList();
1998 void NetConn_Init(void)
2001 lhnetaddress_t tempaddress;
2002 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2003 Cmd_AddCommand("net_stats", Net_Stats_f);
2004 Cmd_AddCommand("net_slist", Net_Slist_f);
2005 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
2006 Cvar_RegisterVariable(&net_slist_queriespersecond);
2007 Cvar_RegisterVariable(&net_slist_queriesperframe);
2008 Cvar_RegisterVariable(&net_slist_timeout);
2009 Cvar_RegisterVariable(&net_slist_maxtries);
2010 Cvar_RegisterVariable(&net_messagetimeout);
2011 Cvar_RegisterVariable(&net_messagerejointimeout);
2012 Cvar_RegisterVariable(&net_connecttimeout);
2013 Cvar_RegisterVariable(&cl_netlocalping);
2014 Cvar_RegisterVariable(&cl_netpacketloss);
2015 Cvar_RegisterVariable(&hostname);
2016 Cvar_RegisterVariable(&developer_networking);
2017 Cvar_RegisterVariable(&cl_netport);
2018 Cvar_RegisterVariable(&sv_netport);
2019 Cvar_RegisterVariable(&net_address);
2020 //Cvar_RegisterVariable(&net_address_ipv6);
2021 Cvar_RegisterVariable(&sv_public);
2022 Cvar_RegisterVariable(&sv_heartbeatperiod);
2023 for (i = 0;sv_masters[i].name;i++)
2024 Cvar_RegisterVariable(&sv_masters[i]);
2025 // 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.
2026 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2028 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2030 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2031 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2034 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2036 // 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
2037 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2039 i = atoi(com_argv[i + 1]);
2040 if (i >= 0 && i < 65536)
2042 Con_Printf("-port option used, setting port cvar to %i\n", i);
2043 Cvar_SetValueQuick(&sv_netport, i);
2046 Con_Printf("-port option used, but %i is not a valid port number\n", i);
2050 net_message.data = net_message_buf;
2051 net_message.maxsize = sizeof(net_message_buf);
2052 net_message.cursize = 0;
2056 void NetConn_Shutdown(void)
2058 NetConn_CloseClientPorts();
2059 NetConn_CloseServerPorts();