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"};
61 /* statistic counters */
62 static int packetsSent = 0;
63 static int packetsReSent = 0;
64 static int packetsReceived = 0;
65 static int receivedDuplicateCount = 0;
66 static int droppedDatagrams = 0;
68 static int unreliableMessagesSent = 0;
69 static int unreliableMessagesReceived = 0;
70 static int reliableMessagesSent = 0;
71 static int reliableMessagesReceived = 0;
73 double masterquerytime = -1000;
74 int masterquerycount = 0;
75 int masterreplycount = 0;
76 int serverquerycount = 0;
77 int serverreplycount = 0;
79 // this is only false if there are still servers left to query
80 int serverlist_querysleep = true;
82 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
83 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
86 lhnetsocket_t *cl_sockets[16];
88 lhnetsocket_t *sv_sockets[16];
90 netconn_t *netconn_list = NULL;
91 mempool_t *netconn_mempool = NULL;
93 cvar_t cl_netport = {0, "cl_port", "0"};
94 cvar_t sv_netport = {0, "port", "26000"};
95 cvar_t net_address = {0, "net_address", "0.0.0.0"};
96 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
98 // ServerList interface
99 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
100 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
102 serverlist_infofield_t serverlist_sortbyfield;
103 qboolean serverlist_sortdescending;
105 int serverlist_viewcount = 0;
106 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
108 int serverlist_cachecount;
109 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
111 qboolean serverlist_consoleoutput;
113 // helper function to insert a value into the viewset
114 // spare entries will be removed
115 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
118 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
119 i = serverlist_viewcount++;
121 i = SERVERLIST_VIEWLISTSIZE - 1;
124 for( ; i > index ; i-- )
125 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
127 serverlist_viewlist[index] = entry;
130 // we suppose serverlist_viewcount to be valid, ie > 0
131 static void _ServerList_ViewList_Helper_Remove( int index )
133 serverlist_viewcount--;
134 for( ; index < serverlist_viewcount ; index++ )
135 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
138 // returns true if A should be inserted before B
139 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
141 int result = 0; // > 0 if for numbers A > B and for text if A < B
143 switch( serverlist_sortbyfield ) {
145 result = A->info.ping - B->info.ping;
147 case SLIF_MAXPLAYERS:
148 result = A->info.maxplayers - B->info.maxplayers;
150 case SLIF_NUMPLAYERS:
151 result = A->info.numplayers - B->info.numplayers;
154 result = A->info.protocol - B->info.protocol;
157 result = strcmp( B->info.cname, A->info.cname );
160 result = strcmp( B->info.game, A->info.game );
163 result = strcmp( B->info.map, A->info.map );
166 result = strcmp( B->info.mod, A->info.mod );
169 result = strcmp( B->info.name, A->info.name );
172 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
176 if( serverlist_sortdescending )
181 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
183 // This should actually be done with some intermediate and end-of-function return
195 case SLMO_GREATEREQUAL:
197 case SLMO_NOTCONTAIN:
200 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
205 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
207 // Same here, also using an intermediate & final return would be more appropriate
211 return *B && !!strstr( A, B ); // we want a real bool
212 case SLMO_NOTCONTAIN:
213 return !*B || !strstr( A, B );
215 return strcmp( A, B ) < 0;
217 return strcmp( A, B ) <= 0;
219 return strcmp( A, B ) == 0;
221 return strcmp( A, B ) > 0;
223 return strcmp( A, B ) != 0;
224 case SLMO_GREATEREQUAL:
225 return strcmp( A, B ) >= 0;
227 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
232 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
234 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
236 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
238 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
240 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
242 if( *mask->info.cname
243 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
246 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
249 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
252 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
255 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
260 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
264 // FIXME: change this to be more readable (...)
265 // now check whether it passes through the masks
266 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
267 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
270 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
271 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
273 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
276 if( !serverlist_viewcount ) {
277 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
280 // ok, insert it, we just need to find out where exactly:
283 // check whether to insert it as new first item
284 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
285 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
287 } // check whether to insert it as new last item
288 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
289 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
293 end = serverlist_viewcount - 1;
294 while( end > start + 1 )
296 mid = (start + end) / 2;
297 // test the item that lies in the middle between start and end
298 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
299 // the item has to be in the upper half
302 // the item has to be in the lower half
305 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
308 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
311 for( i = 0; i < serverlist_viewcount; i++ )
313 if (serverlist_viewlist[i] == entry)
315 _ServerList_ViewList_Helper_Remove(i);
321 void ServerList_RebuildViewList(void)
325 serverlist_viewcount = 0;
326 for( i = 0 ; i < serverlist_cachecount ; i++ )
327 if( serverlist_cache[i].query == SQS_QUERIED )
328 ServerList_ViewList_Insert( &serverlist_cache[i] );
331 void ServerList_ResetMasks(void)
333 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
334 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
338 static void _ServerList_Test(void)
341 for( i = 0 ; i < 1024 ; i++ ) {
342 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
343 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
344 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, 128, "Black's ServerList Test %i", i );
345 serverlist_cache[serverlist_cachecount].finished = true;
346 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
347 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
348 serverlist_cachecount++;
353 void ServerList_QueryList(void)
355 masterquerytime = realtime;
356 masterquerycount = 0;
357 masterreplycount = 0;
358 serverquerycount = 0;
359 serverreplycount = 0;
360 serverlist_cachecount = 0;
361 serverlist_viewcount = 0;
362 serverlist_consoleoutput = false;
364 //_ServerList_Test();
366 NetConn_QueryMasters();
371 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
373 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
377 if (cl_netpacketloss.integer)
378 for (i = 0;i < cl_numsockets;i++)
379 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
381 if (developer_networking.integer)
383 char addressstring[128], addressstring2[128];
384 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
387 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
388 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
389 Com_HexDumpToConsole(data, length);
392 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
397 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
401 if (cl_netpacketloss.integer)
402 for (i = 0;i < cl_numsockets;i++)
403 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
405 ret = LHNET_Write(mysocket, data, length, peeraddress);
406 if (developer_networking.integer)
408 char addressstring[128], addressstring2[128];
409 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
410 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
411 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
412 Com_HexDumpToConsole(data, length);
417 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
419 // note this does not include the trailing NULL because we add that in the parser
420 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
423 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
425 unsigned int packetLen;
426 unsigned int dataLen;
428 unsigned int *header;
431 if (data->cursize == 0)
432 Sys_Error("Datagram_SendMessage: zero length message\n");
434 if (data->cursize > (int)sizeof(conn->sendMessage))
435 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
437 if (conn->canSend == false)
438 Sys_Error("SendMessage: called with canSend == false\n");
441 memcpy(conn->sendMessage, data->data, data->cursize);
442 conn->sendMessageLength = data->cursize;
444 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
446 dataLen = conn->sendMessageLength;
451 dataLen = MAX_PACKETFRAGMENT;
455 packetLen = NET_HEADERSIZE + dataLen;
457 header = (void *)sendbuffer;
458 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
459 header[1] = BigLong(conn->sendSequence);
460 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
462 conn->sendSequence++;
463 conn->canSend = false;
465 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
468 conn->lastSendTime = realtime;
470 reliableMessagesSent++;
474 static void NetConn_SendMessageNext(netconn_t *conn)
476 unsigned int packetLen;
477 unsigned int dataLen;
479 unsigned int *header;
481 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
483 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
485 dataLen = conn->sendMessageLength;
490 dataLen = MAX_PACKETFRAGMENT;
494 packetLen = NET_HEADERSIZE + dataLen;
496 header = (void *)sendbuffer;
497 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
498 header[1] = BigLong(conn->sendSequence);
499 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
501 conn->sendSequence++;
502 conn->sendNext = false;
504 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
507 conn->lastSendTime = realtime;
512 static void NetConn_ReSendMessage(netconn_t *conn)
514 unsigned int packetLen;
515 unsigned int dataLen;
517 unsigned int *header;
519 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
521 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
523 dataLen = conn->sendMessageLength;
528 dataLen = MAX_PACKETFRAGMENT;
532 packetLen = NET_HEADERSIZE + dataLen;
534 header = (void *)sendbuffer;
535 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
536 header[1] = BigLong(conn->sendSequence - 1);
537 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
539 conn->sendNext = false;
541 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
544 conn->lastSendTime = realtime;
549 qboolean NetConn_CanSendMessage(netconn_t *conn)
551 return conn->canSend;
554 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
559 packetLen = NET_HEADERSIZE + data->cursize;
562 if (data->cursize == 0)
563 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
565 if (packetLen > (int)sizeof(sendbuffer))
566 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
569 header = (void *)sendbuffer;
570 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
571 header[1] = BigLong(conn->unreliableSendSequence);
572 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
574 conn->unreliableSendSequence++;
576 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
580 unreliableMessagesSent++;
584 void NetConn_CloseClientPorts(void)
586 for (;cl_numsockets > 0;cl_numsockets--)
587 if (cl_sockets[cl_numsockets - 1])
588 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
591 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
593 lhnetaddress_t address;
595 char addressstring2[1024];
596 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
598 if ((s = LHNET_OpenSocket_Connectionless(&address)))
600 cl_sockets[cl_numsockets++] = s;
601 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
602 Con_Printf("Client opened a socket on address %s\n", addressstring2);
606 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
607 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
611 Con_Printf("Client unable to parse address %s\n", addressstring);
614 void NetConn_OpenClientPorts(void)
617 NetConn_CloseClientPorts();
618 port = bound(0, cl_netport.integer, 65535);
619 if (cl_netport.integer != port)
620 Cvar_SetValueQuick(&cl_netport, port);
621 Con_Printf("Client using port %i\n", port);
622 NetConn_OpenClientPort("local:2", 0);
623 NetConn_OpenClientPort(net_address.string, port);
624 //NetConn_OpenClientPort(net_address_ipv6.string, port);
627 void NetConn_CloseServerPorts(void)
629 for (;sv_numsockets > 0;sv_numsockets--)
630 if (sv_sockets[sv_numsockets - 1])
631 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
634 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
636 lhnetaddress_t address;
638 char addressstring2[1024];
639 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
641 if ((s = LHNET_OpenSocket_Connectionless(&address)))
643 sv_sockets[sv_numsockets++] = s;
644 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
645 Con_Printf("Server listening on address %s\n", addressstring2);
649 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
650 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
654 Con_Printf("Server unable to parse address %s\n", addressstring);
657 void NetConn_OpenServerPorts(int opennetports)
660 NetConn_CloseServerPorts();
661 port = bound(0, sv_netport.integer, 65535);
664 Con_Printf("Server using port %i\n", port);
665 if (sv_netport.integer != port)
666 Cvar_SetValueQuick(&sv_netport, port);
667 if (cls.state != ca_dedicated)
668 NetConn_OpenServerPort("local:1", 0);
671 NetConn_OpenServerPort(net_address.string, port);
672 //NetConn_OpenServerPort(net_address_ipv6.string, port);
674 if (sv_numsockets == 0)
675 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
678 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
680 int i, a = LHNETADDRESS_GetAddressType(address);
681 for (i = 0;i < cl_numsockets;i++)
682 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
683 return cl_sockets[i];
687 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
689 int i, a = LHNETADDRESS_GetAddressType(address);
690 for (i = 0;i < sv_numsockets;i++)
691 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
692 return sv_sockets[i];
696 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
699 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
700 conn->mysocket = mysocket;
701 conn->peeraddress = *peeraddress;
702 conn->canSend = true;
703 conn->lastMessageTime = realtime;
704 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
705 // reduce effectiveness of connection request floods
706 conn->timeout = realtime + net_connecttimeout.value;
707 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
708 conn->next = netconn_list;
713 void NetConn_Close(netconn_t *conn)
716 // remove connection from list
717 if (conn == netconn_list)
718 netconn_list = conn->next;
721 for (c = netconn_list;c;c = c->next)
725 c->next = conn->next;
729 // not found in list, we'll avoid crashing here...
737 static int clientport = -1;
738 static int clientport2 = -1;
739 static int hostport = -1;
740 static void NetConn_UpdateServerStuff(void)
742 if (cls.state != ca_dedicated)
744 if (clientport2 != cl_netport.integer)
746 clientport2 = cl_netport.integer;
747 if (cls.state == ca_connected)
748 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
750 if (cls.state == ca_disconnected && clientport != clientport2)
752 clientport = clientport2;
753 NetConn_CloseClientPorts();
755 if (cl_numsockets == 0)
756 NetConn_OpenClientPorts();
759 if (hostport != sv_netport.integer)
761 hostport = sv_netport.integer;
763 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
767 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
771 unsigned int sequence;
776 qlength = (unsigned int)BigLong(((int *)data)[0]);
777 flags = qlength & ~NETFLAG_LENGTH_MASK;
778 qlength &= NETFLAG_LENGTH_MASK;
779 // control packets were already handled
780 if (!(flags & NETFLAG_CTL) && qlength == length)
782 sequence = BigLong(((int *)data)[1]);
786 if (flags & NETFLAG_UNRELIABLE)
788 if (sequence >= conn->unreliableReceiveSequence)
790 if (sequence > conn->unreliableReceiveSequence)
792 count = sequence - conn->unreliableReceiveSequence;
793 droppedDatagrams += count;
794 Con_DPrintf("Dropped %u datagram(s)\n", count);
796 conn->unreliableReceiveSequence = sequence + 1;
797 conn->lastMessageTime = realtime;
798 conn->timeout = realtime + net_messagetimeout.value;
799 unreliableMessagesReceived++;
802 SZ_Clear(&net_message);
803 SZ_Write(&net_message, data, length);
809 Con_DPrint("Got a stale datagram\n");
812 else if (flags & NETFLAG_ACK)
814 if (sequence == (conn->sendSequence - 1))
816 if (sequence == conn->ackSequence)
819 if (conn->ackSequence != conn->sendSequence)
820 Con_DPrint("ack sequencing error\n");
821 conn->lastMessageTime = realtime;
822 conn->timeout = realtime + net_messagetimeout.value;
823 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
824 if (conn->sendMessageLength > 0)
826 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
827 conn->sendNext = true;
828 NetConn_SendMessageNext(conn);
832 conn->sendMessageLength = 0;
833 conn->canSend = true;
837 Con_DPrint("Duplicate ACK received\n");
840 Con_DPrint("Stale ACK received\n");
843 else if (flags & NETFLAG_DATA)
845 unsigned int temppacket[2];
846 temppacket[0] = BigLong(8 | NETFLAG_ACK);
847 temppacket[1] = BigLong(sequence);
848 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
849 if (sequence == conn->receiveSequence)
851 conn->lastMessageTime = realtime;
852 conn->timeout = realtime + net_messagetimeout.value;
853 conn->receiveSequence++;
854 if( conn->receiveMessageLength + length <= sizeof( conn->receiveMessage ) ) {
855 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
856 conn->receiveMessageLength += length;
858 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
859 "Dropping the message!\n", sequence );
860 conn->receiveMessageLength = 0;
863 if (flags & NETFLAG_EOM)
865 reliableMessagesReceived++;
866 length = conn->receiveMessageLength;
867 conn->receiveMessageLength = 0;
870 SZ_Clear(&net_message);
871 SZ_Write(&net_message, conn->receiveMessage, length);
878 receivedDuplicateCount++;
886 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
888 cls.connect_trying = false;
889 M_Update_Return_Reason("");
890 // the connection request succeeded, stop current connection and set up a new connection
892 // if we're connecting to a remote server, shut down any local server
893 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
894 Host_ShutdownServer (false);
895 // allocate a net connection to keep track of things
896 cls.netcon = NetConn_Open(mysocket, peeraddress);
897 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
900 cls.demonum = -1; // not in the demo loop now
901 cls.state = ca_connected;
902 cls.signon = 0; // need all the signon messages before playing
905 int NetConn_IsLocalGame(void)
907 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
912 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
916 char *string, addressstring2[128], cname[128], ipstring[32];
917 char stringbuf[16384];
919 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
921 // received a command string - strip off the packaging and put it
922 // into our string buffer with NULL termination
925 length = min(length, (int)sizeof(stringbuf) - 1);
926 memcpy(stringbuf, data, length);
927 stringbuf[length] = 0;
930 if (developer.integer)
932 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
933 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
934 Com_HexDumpToConsole(data, length);
937 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
939 char protocolnames[1400];
940 Protocol_Names(protocolnames, sizeof(protocolnames));
941 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
942 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
943 M_Update_Return_Reason("Got challenge response");
944 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
947 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
949 M_Update_Return_Reason("Accepted");
950 NetConn_ConnectionEstablished(mysocket, peeraddress);
953 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
955 char rejectreason[32];
956 cls.connect_trying = false;
958 length = max(length - 7, (int)sizeof(rejectreason) - 1);
959 memcpy(rejectreason, string, length);
960 rejectreason[length] = 0;
961 M_Update_Return_Reason(rejectreason);
964 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
966 serverlist_info_t *info;
971 // serverlist only uses text addresses
972 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
973 // search the cache for this server and update it
974 for( n = 0; n < serverlist_cachecount; n++ )
975 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
977 if( n == serverlist_cachecount ) {
978 // LAN search doesnt require an answer from the master server so we wont
979 // know the ping nor will it be initialized already...
982 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
985 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
986 // store the data the engine cares about (address and ping)
987 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
988 serverlist_cache[serverlist_cachecount].info.ping = 100000;
989 serverlist_cache[serverlist_cachecount].querytime = realtime;
990 // if not in the slist menu we should print the server to console
991 if (serverlist_consoleoutput) {
992 Con_Printf("querying %s\n", ipstring);
995 ++serverlist_cachecount;
998 info = &serverlist_cache[n].info;
999 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1000 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1001 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1002 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1003 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1004 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1005 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1007 if (info->ping == 100000)
1010 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1011 pingtime = bound(0, pingtime, 9999);
1013 info->ping = pingtime;
1015 // legacy/old stuff move it to the menu ASAP
1017 // build description strings for the things users care about
1018 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);
1019 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);
1020 // if ping is especially high, display it as such
1021 if (pingtime >= 300)
1023 // orange numbers (lower block)
1024 for (i = 0;i < 5;i++)
1025 if (serverlist_cache[n].line1[i] != ' ')
1026 serverlist_cache[n].line1[i] += 128;
1028 else if (pingtime >= 200)
1030 // yellow numbers (in upper block)
1031 for (i = 0;i < 5;i++)
1032 if (serverlist_cache[n].line1[i] != ' ')
1033 serverlist_cache[n].line1[i] -= 30;
1035 if( serverlist_cache[n].query == SQS_QUERIED ) {
1036 ServerList_ViewList_Remove( &serverlist_cache[n] );
1038 // if not in the slist menu we should print the server to console (if wanted)
1039 else if( serverlist_consoleoutput )
1040 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1041 // and finally, update the view set
1042 ServerList_ViewList_Insert( &serverlist_cache[n] );
1043 serverlist_cache[n].query = SQS_QUERIED;
1047 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1049 // Extract the IP addresses
1053 if (serverlist_consoleoutput)
1054 Con_Print("received server list...\n");
1055 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1059 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1060 if (developer.integer)
1061 Con_Printf("Requesting info from server %s\n", ipstring);
1062 // ignore the rest of the message if the serverlist is full
1063 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1065 // also ignore it if we have already queried it (other master server response)
1066 for( n = 0 ; n < serverlist_cachecount ; n++ )
1067 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1069 if( n >= serverlist_cachecount )
1073 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1074 // store the data the engine cares about (address and ping)
1075 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1076 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1077 serverlist_cache[serverlist_cachecount].query = SQS_PENDING;
1079 ++serverlist_cachecount;
1082 // move on to next address in packet
1086 // begin or resume serverlist queries
1087 serverlist_querysleep = false;
1091 if (!strncmp(string, "ping", 4))
1093 if (developer.integer)
1094 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1095 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1098 if (!strncmp(string, "ack", 3))
1101 // we may not have liked the packet, but it was a command packet, so
1102 // we're done processing this packet now
1105 // netquake control packets, supported for compatibility only
1106 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1111 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1115 if (developer.integer)
1116 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1117 if (cls.connect_trying)
1119 lhnetaddress_t clientportaddress;
1120 clientportaddress = *peeraddress;
1123 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1126 LHNETADDRESS_SetPort(&clientportaddress, port);
1128 M_Update_Return_Reason("Accepted");
1129 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1133 if (developer.integer)
1134 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1135 cls.connect_trying = false;
1136 M_Update_Return_Reason(data);
1139 case CCREP_SERVER_INFO:
1140 if (developer.integer)
1141 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1142 if (cls.state != ca_dedicated)
1144 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1145 // string we just ignore it and keep the real address
1147 // serverlist only uses text addresses
1148 cname = UDP_AddrToString(readaddr);
1149 // search the cache for this server
1150 for (n = 0; n < hostCacheCount; n++)
1151 if (!strcmp(cname, serverlist[n].cname))
1154 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1157 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1158 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1159 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1160 serverlist[n].users = MSG_ReadByte();
1161 serverlist[n].maxusers = MSG_ReadByte();
1163 if (c != NET_PROTOCOL_VERSION)
1165 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1166 strcpy(serverlist[n].name, "*");
1167 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1169 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1173 case CCREP_PLAYER_INFO:
1174 // we got a CCREP_PLAYER_INFO??
1175 //if (developer.integer)
1176 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1178 case CCREP_RULE_INFO:
1179 // we got a CCREP_RULE_INFO??
1180 //if (developer.integer)
1181 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1187 // we may not have liked the packet, but it was a valid control
1188 // packet, so we're done processing this packet now
1192 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)
1193 CL_ParseServerMessage();
1197 void NetConn_QueryQueueFrame(void)
1202 static double querycounter = 0;
1204 if (serverlist_querysleep)
1207 // each time querycounter reaches 1.0 issue a query
1208 querycounter += host_realframetime * net_slist_queriespersecond.value;
1209 maxqueries = (int)querycounter;
1210 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1211 querycounter -= maxqueries;
1213 // scan serverlist and issue queries as needed
1214 // (note: this aborts immediately if maxqueries is 0)
1215 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1217 if( serverlist_cache[ index ].query == SQS_PENDING )
1219 lhnetaddress_t address;
1222 LHNETADDRESS_FromString(&address, serverlist_cache[ index ].info.cname, 0);
1223 for (socket = 0; socket < cl_numsockets ; socket++) {
1224 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1227 serverlist_cache[ index ].querytime = realtime;
1228 serverlist_cache[ index ].query = SQS_QUERYING;
1230 // if not in the slist menu we should print the server to console
1231 if (serverlist_consoleoutput)
1232 Con_Printf("querying %s\n", serverlist_cache[ index ].info.cname);
1239 // if we didn't find any to query, go back to sleep
1240 if (index == serverlist_cachecount)
1241 serverlist_querysleep = true;
1244 void NetConn_ClientFrame(void)
1247 lhnetaddress_t peeraddress;
1249 NetConn_UpdateServerStuff();
1250 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1252 if (cls.connect_remainingtries == 0)
1253 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1254 cls.connect_nextsendtime = realtime + 1;
1255 cls.connect_remainingtries--;
1256 if (cls.connect_remainingtries <= -10)
1258 cls.connect_trying = false;
1259 M_Update_Return_Reason("Connect: Failed");
1262 // try challenge first (newer server)
1263 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1264 // then try netquake as a fallback (old server, or netquake)
1265 SZ_Clear(&net_message);
1266 // save space for the header, filled in later
1267 MSG_WriteLong(&net_message, 0);
1268 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1269 MSG_WriteString(&net_message, "QUAKE");
1270 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1271 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1272 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1273 SZ_Clear(&net_message);
1275 for (i = 0;i < cl_numsockets;i++) {
1276 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0) {
1277 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1280 NetConn_QueryQueueFrame();
1281 if (cls.netcon && realtime > cls.netcon->timeout)
1283 Con_Print("Connection timed out\n");
1285 Host_ShutdownServer (false);
1287 for (conn = netconn_list;conn;conn = conn->next)
1288 NetConn_ReSendMessage(conn);
1291 #define MAX_CHALLENGES 128
1294 lhnetaddress_t address;
1298 challenge[MAX_CHALLENGES];
1300 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1304 for (i = 0;i < bufferlength - 1;i++)
1308 c = rand () % (127 - 33) + 33;
1309 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1315 extern void SV_SendServerinfo (client_t *client);
1316 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1318 int i, n, ret, clientnum, responselength, best;
1322 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1326 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1328 // received a command string - strip off the packaging and put it
1329 // into our string buffer with NULL termination
1332 length = min(length, (int)sizeof(stringbuf) - 1);
1333 memcpy(stringbuf, data, length);
1334 stringbuf[length] = 0;
1337 if (developer.integer)
1339 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1340 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1341 Com_HexDumpToConsole(data, length);
1344 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1346 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1348 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1350 if (besttime > challenge[i].time)
1351 besttime = challenge[best = i].time;
1353 // if we did not find an exact match, choose the oldest and
1354 // update address and string
1355 if (i == MAX_CHALLENGES)
1358 challenge[i].address = *peeraddress;
1359 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1361 challenge[i].time = realtime;
1362 // send the challenge
1363 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1366 if (length > 8 && !memcmp(string, "connect\\", 8))
1370 if ((s = SearchInfostring(string, "challenge")))
1372 // validate the challenge
1373 for (i = 0;i < MAX_CHALLENGES;i++)
1374 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1376 if (i < MAX_CHALLENGES)
1378 // check engine protocol
1379 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1381 if (developer.integer)
1382 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1383 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1387 // see if this is a duplicate connection request
1388 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1389 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1391 if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1393 // client is still trying to connect,
1394 // so we send a duplicate reply
1395 if (developer.integer)
1396 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1397 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1400 else if (clientnum < svs.maxclients)
1402 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1404 // client crashed and is coming back, keep their stuff intact
1405 SV_SendServerinfo(client);
1406 //host_client = client;
1407 //SV_DropClient (true);
1414 // this is a new client, find a slot
1415 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1416 if (!client->active)
1418 if (clientnum < svs.maxclients)
1420 // prepare the client struct
1421 if ((conn = NetConn_Open(mysocket, peeraddress)))
1423 // allocated connection
1424 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1425 if (developer.integer)
1426 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1427 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1428 // now set up the client
1429 SV_ConnectClient(clientnum, conn);
1430 NetConn_Heartbeat(1);
1436 if (developer.integer)
1437 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1438 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1446 if (length >= 7 && !memcmp(string, "getinfo", 7))
1448 const char *challenge = NULL;
1449 // If there was a challenge in the getinfo message
1450 if (length > 8 && string[7] == ' ')
1451 challenge = string + 8;
1452 for (i = 0, n = 0;i < svs.maxclients;i++)
1453 if (svs.clients[i].active)
1455 responselength = dpsnprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1456 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1457 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1458 gamename, com_modname, svs.maxclients, n,
1459 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1460 // does it fit in the buffer?
1461 if (responselength >= 0)
1463 if (developer.integer)
1464 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1465 NetConn_WriteString(mysocket, response, peeraddress);
1470 if (!strncmp(string, "ping", 4))
1472 if (developer.integer)
1473 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1474 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1477 if (!strncmp(string, "ack", 3))
1480 // we may not have liked the packet, but it was a command packet, so
1481 // we're done processing this packet now
1484 // LordHavoc: disabled netquake control packet support in server
1488 // netquake control packets, supported for compatibility only
1489 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1494 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1498 //if (developer.integer)
1499 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1500 if (length >= (int)strlen("QUAKE") + 1 + 1)
1502 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1504 if (developer.integer)
1505 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1506 SZ_Clear(&net_message);
1507 // save space for the header, filled in later
1508 MSG_WriteLong(&net_message, 0);
1509 MSG_WriteByte(&net_message, CCREP_REJECT);
1510 MSG_WriteString(&net_message, "Incompatible version.\n");
1511 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1512 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1513 SZ_Clear(&net_message);
1517 // see if this is a duplicate connection request
1518 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1519 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1521 if (clientnum < svs.maxclients)
1523 // duplicate connection request
1524 if (realtime - client->connecttime < 2.0)
1526 // client is still trying to connect,
1527 // so we send a duplicate reply
1528 if (developer.integer)
1529 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1530 SZ_Clear(&net_message);
1531 // save space for the header, filled in later
1532 MSG_WriteLong(&net_message, 0);
1533 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1534 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1535 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1536 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1537 SZ_Clear(&net_message);
1540 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1542 SV_SendServerinfo(client);
1543 // the old client hasn't sent us anything
1544 // in quite a while, so kick off and let
1545 // the retry take care of it...
1546 //host_client = client;
1547 //SV_DropClient (true);
1553 // this is a new client, find a slot
1554 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1555 if (!client->active)
1557 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1559 // connect to the client
1560 // everything is allocated, just fill in the details
1561 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1562 if (developer.integer)
1563 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1564 // send back the info about the server connection
1565 SZ_Clear(&net_message);
1566 // save space for the header, filled in later
1567 MSG_WriteLong(&net_message, 0);
1568 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1569 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1570 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1571 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1572 SZ_Clear(&net_message);
1573 // now set up the client struct
1574 SV_ConnectClient(clientnum, conn);
1575 NetConn_Heartbeat(1);
1579 //if (developer.integer)
1580 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1581 // no room; try to let player know
1582 SZ_Clear(&net_message);
1583 // save space for the header, filled in later
1584 MSG_WriteLong(&net_message, 0);
1585 MSG_WriteByte(&net_message, CCREP_REJECT);
1586 MSG_WriteString(&net_message, "Server is full.\n");
1587 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1588 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1589 SZ_Clear(&net_message);
1596 case CCREQ_SERVER_INFO:
1597 if (developer.integer)
1598 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1599 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1601 if (developer.integer)
1602 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1603 SZ_Clear(&net_message);
1604 // save space for the header, filled in later
1605 MSG_WriteLong(&net_message, 0);
1606 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1607 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1608 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1609 MSG_WriteString(&net_message, hostname.string);
1610 MSG_WriteString(&net_message, sv.name);
1611 MSG_WriteByte(&net_message, net_activeconnections);
1612 MSG_WriteByte(&net_message, svs.maxclients);
1613 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1614 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1615 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1616 SZ_Clear(&net_message);
1619 case CCREQ_PLAYER_INFO:
1620 if (developer.integer)
1621 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1624 int playerNumber, activeNumber, clientNumber;
1627 playerNumber = MSG_ReadByte();
1629 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1630 if (client->active && ++activeNumber == playerNumber)
1632 if (clientNumber != svs.maxclients)
1634 SZ_Clear(&net_message);
1635 // save space for the header, filled in later
1636 MSG_WriteLong(&net_message, 0);
1637 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1638 MSG_WriteByte(&net_message, playerNumber);
1639 MSG_WriteString(&net_message, client->name);
1640 MSG_WriteLong(&net_message, client->colors);
1641 MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1642 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1643 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
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);
1650 case CCREQ_RULE_INFO:
1651 if (developer.integer)
1652 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1658 // find the search start location
1659 prevCvarName = MSG_ReadString();
1660 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1662 // send the response
1663 SZ_Clear(&net_message);
1664 // save space for the header, filled in later
1665 MSG_WriteLong(&net_message, 0);
1666 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1669 MSG_WriteString(&net_message, var->name);
1670 MSG_WriteString(&net_message, var->string);
1672 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1673 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1674 SZ_Clear(&net_message);
1681 // we may not have liked the packet, but it was a valid control
1682 // packet, so we're done processing this packet now
1687 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1689 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1691 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1692 SV_ReadClientMessage();
1700 void NetConn_ServerFrame(void)
1703 lhnetaddress_t peeraddress;
1705 NetConn_UpdateServerStuff();
1706 for (i = 0;i < sv_numsockets;i++)
1707 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1708 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1709 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1711 // never timeout loopback connections
1712 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1714 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1715 SV_DropClient(false);
1718 for (conn = netconn_list;conn;conn = conn->next)
1719 NetConn_ReSendMessage(conn);
1722 void NetConn_QueryMasters(void)
1726 lhnetaddress_t masteraddress;
1727 lhnetaddress_t broadcastaddress;
1730 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1733 // 26000 is the default quake server port, servers on other ports will not
1735 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1736 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1738 for (i = 0;i < cl_numsockets;i++)
1742 // search LAN for Quake servers
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, CCREQ_SERVER_INFO);
1747 MSG_WriteString(&net_message, "QUAKE");
1748 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1749 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1750 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1751 SZ_Clear(&net_message);
1753 // search LAN for DarkPlaces servers
1754 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1756 // build the getservers message to send to the master servers
1757 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1760 for (masternum = 0;sv_masters[masternum].name;masternum++)
1762 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1765 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1770 if (!masterquerycount)
1772 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1773 M_Update_Return_Reason("No network");
1777 void NetConn_Heartbeat(int priority)
1779 lhnetaddress_t masteraddress;
1781 lhnetsocket_t *mysocket;
1783 // if it's a state change (client connected), limit next heartbeat to no
1784 // more than 30 sec in the future
1785 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1786 nextheartbeattime = realtime + 30.0;
1788 // limit heartbeatperiod to 30 to 270 second range,
1789 // lower limit is to avoid abusing master servers with excess traffic,
1790 // upper limit is to avoid timing out on the master server (which uses
1792 if (sv_heartbeatperiod.value < 30)
1793 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1794 if (sv_heartbeatperiod.value > 270)
1795 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1797 // make advertising optional and don't advertise singleplayer games, and
1798 // only send a heartbeat as often as the admin wants
1799 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1801 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1802 for (masternum = 0;sv_masters[masternum].name;masternum++)
1803 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1804 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1808 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1811 qbyte sent[MAX_SCOREBOARD];
1813 memset(sent, 0, sizeof(sent));
1815 // simultaneously wait for the first CanSendMessage and send the message,
1816 // then wait for a second CanSendMessage (verifying it was received), or
1817 // the client drops and is no longer counted
1818 // the loop aborts when either it runs out of clients to send to, or a
1820 blocktime += Sys_DoubleTime();
1824 NetConn_ClientFrame();
1825 NetConn_ServerFrame();
1826 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1828 if (host_client->netconnection)
1830 if (NetConn_CanSendMessage(host_client->netconnection))
1833 NetConn_SendReliableMessage(host_client->netconnection, data);
1836 if (!NetConn_CanSendMessage(host_client->netconnection))
1841 while (count && Sys_DoubleTime() < blocktime);
1845 static void Net_Heartbeat_f(void)
1848 NetConn_Heartbeat(2);
1850 Con_Print("No server running, can not heartbeat to master server.\n");
1853 void PrintStats(netconn_t *conn)
1855 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1858 void Net_Stats_f(void)
1861 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1862 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1863 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1864 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1865 Con_Printf("packetsSent = %i\n", packetsSent);
1866 Con_Printf("packetsReSent = %i\n", packetsReSent);
1867 Con_Printf("packetsReceived = %i\n", packetsReceived);
1868 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1869 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1870 Con_Print("connections =\n");
1871 for (conn = netconn_list;conn;conn = conn->next)
1875 void Net_Slist_f(void)
1877 ServerList_ResetMasks();
1878 serverlist_sortbyfield = SLIF_PING;
1879 serverlist_sortdescending = false;
1880 if (m_state != m_slist) {
1881 Con_Print("Sending requests to master servers\n");
1882 ServerList_QueryList();
1883 serverlist_consoleoutput = true;
1884 Con_Print("Listening for replies...\n");
1886 ServerList_QueryList();
1889 void NetConn_Init(void)
1892 lhnetaddress_t tempaddress;
1893 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
1894 Cmd_AddCommand("net_stats", Net_Stats_f);
1895 Cmd_AddCommand("net_slist", Net_Slist_f);
1896 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1897 Cvar_RegisterVariable(&net_slist_queriespersecond);
1898 Cvar_RegisterVariable(&net_slist_queriesperframe);
1899 Cvar_RegisterVariable(&net_messagetimeout);
1900 Cvar_RegisterVariable(&net_messagerejointimeout);
1901 Cvar_RegisterVariable(&net_connecttimeout);
1902 Cvar_RegisterVariable(&cl_netlocalping);
1903 Cvar_RegisterVariable(&cl_netpacketloss);
1904 Cvar_RegisterVariable(&hostname);
1905 Cvar_RegisterVariable(&developer_networking);
1906 Cvar_RegisterVariable(&cl_netport);
1907 Cvar_RegisterVariable(&sv_netport);
1908 Cvar_RegisterVariable(&net_address);
1909 //Cvar_RegisterVariable(&net_address_ipv6);
1910 Cvar_RegisterVariable(&sv_public);
1911 Cvar_RegisterVariable(&sv_heartbeatperiod);
1912 for (i = 0;sv_masters[i].name;i++)
1913 Cvar_RegisterVariable(&sv_masters[i]);
1914 // 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.
1915 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1917 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1919 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1920 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1923 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1925 // 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
1926 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1928 i = atoi(com_argv[i + 1]);
1929 if (i >= 0 && i < 65536)
1931 Con_Printf("-port option used, setting port cvar to %i\n", i);
1932 Cvar_SetValueQuick(&sv_netport, i);
1935 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1939 net_message.data = net_message_buf;
1940 net_message.maxsize = sizeof(net_message_buf);
1941 net_message.cursize = 0;
1945 void NetConn_Shutdown(void)
1947 NetConn_CloseClientPorts();
1948 NetConn_CloseServerPorts();