2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define MASTER_PORT 27950
28 cvar_t sv_public = {0, "sv_public", "1"};
29 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "180"};
31 // FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat)
32 static cvar_t sv_masters [] =
34 {CVAR_SAVE, "sv_master1", ""},
35 {CVAR_SAVE, "sv_master2", ""},
36 {CVAR_SAVE, "sv_master3", ""},
37 {CVAR_SAVE, "sv_master4", ""},
38 {0, "sv_masterextra1", "69.59.212.88"}, // ghdigital.com
39 {0, "sv_masterextra2", "66.169.205.13"}, // dpmaster.deathmask.net
40 {0, "sv_masterextra3", "12.166.196.192"}, // blaze.mindphukd.org
44 static double nextheartbeattime = 0;
46 sizebuf_t net_message;
48 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
49 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
50 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
51 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
52 cvar_t developer_networking = {0, "developer_networking", "0"};
54 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
55 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
58 /* statistic counters */
59 static int packetsSent = 0;
60 static int packetsReSent = 0;
61 static int packetsReceived = 0;
62 static int receivedDuplicateCount = 0;
63 static int droppedDatagrams = 0;
65 static int unreliableMessagesSent = 0;
66 static int unreliableMessagesReceived = 0;
67 static int reliableMessagesSent = 0;
68 static int reliableMessagesReceived = 0;
70 double masterquerytime = -1000;
71 int masterquerycount = 0;
72 int masterreplycount = 0;
73 int serverquerycount = 0;
74 int serverreplycount = 0;
76 static qbyte sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
77 static qbyte readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
80 lhnetsocket_t *cl_sockets[16];
82 lhnetsocket_t *sv_sockets[16];
84 netconn_t *netconn_list = NULL;
85 mempool_t *netconn_mempool = NULL;
87 cvar_t cl_netport = {0, "cl_port", "0"};
88 cvar_t sv_netport = {0, "port", "26000"};
89 cvar_t net_address = {0, "net_address", "0.0.0.0"};
90 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
92 // ServerList interface
93 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
94 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
96 serverlist_infofield_t serverlist_sortbyfield;
97 qboolean serverlist_sortdescending;
99 int serverlist_viewcount = 0;
100 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
102 int serverlist_cachecount;
103 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
105 qboolean serverlist_consoleoutput;
107 // helper function to insert a value into the viewset
108 // spare entries will be removed
109 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
112 if( serverlist_viewcount == SERVERLIST_VIEWLISTSIZE )
115 for( i = serverlist_viewcount ; i > index ; i-- )
116 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
118 serverlist_viewlist[index] = entry;
119 serverlist_viewcount++;
122 // we suppose serverlist_viewcount to be valid, ie > 0
123 static void _ServerList_ViewList_Helper_Remove( int index )
125 serverlist_viewcount--;
126 for( ; index < serverlist_viewcount ; index++ )
127 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
130 // returns true if A should be inserted before B
131 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
133 int result = 0; // > 0 if for numbers A > B and for text if A < B
135 if( serverlist_sortbyfield == SLIF_PING )
136 result = A->info.ping - B->info.ping;
137 else if( serverlist_sortbyfield == SLIF_MAXPLAYERS )
138 result = A->info.maxplayers - B->info.maxplayers;
139 else if( serverlist_sortbyfield == SLIF_NUMPLAYERS )
140 result = A->info.numplayers - B->info.numplayers;
141 else if( serverlist_sortbyfield == SLIF_PROTOCOL )
142 result = A->info.protocol - B->info.protocol;
143 else if( serverlist_sortbyfield == SLIF_CNAME )
144 result = strcmp( B->info.cname, A->info.cname );
145 else if( serverlist_sortbyfield == SLIF_GAME )
146 result = strcmp( B->info.game, A->info.game );
147 else if( serverlist_sortbyfield == SLIF_MAP )
148 result = strcmp( B->info.map, A->info.map );
149 else if( serverlist_sortbyfield == SLIF_MOD )
150 result = strcmp( B->info.mod, A->info.mod );
151 else if( serverlist_sortbyfield == SLIF_NAME )
152 result = strcmp( B->info.name, A->info.name );
154 if( serverlist_sortdescending )
159 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
161 if( op == SLMO_LESS )
163 else if( op == SLMO_LESSEQUAL )
165 else if( op == SLMO_EQUAL )
167 else if( op == SLMO_GREATER )
169 else if( op == SLMO_NOTEQUAL )
171 else // SLMO_GREATEREQUAL
175 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
177 if( op == SLMO_CONTAINS ) // A info B mask
178 return *B && !!strstr( A, B ); // we want a real bool
179 else if( op == SLMO_NOTCONTAIN )
180 return !*B || !strstr( A, B );
181 else if( op == SLMO_LESS )
182 return strcmp( A, B ) < 0;
183 else if( op == SLMO_LESSEQUAL )
184 return strcmp( A, B ) <= 0;
185 else if( op == SLMO_EQUAL )
186 return strcmp( A, B ) == 0;
187 else if( op == SLMO_GREATER )
188 return strcmp( A, B ) > 0;
189 else if( op == SLMO_NOTEQUAL )
190 return strcmp( A, B ) != 0;
191 else // SLMO_GREATEREQUAL
192 return strcmp( A, B ) >= 0;
195 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
197 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
199 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
201 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
203 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
205 if( *mask->info.cname
206 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
209 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
212 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
215 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
218 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
223 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
227 if( serverlist_viewcount == SERVERLIST_VIEWLISTSIZE )
230 // now check whether it passes through the masks
231 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
232 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
235 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
236 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
238 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
241 if( !serverlist_viewcount ) {
242 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
245 // ok, insert it, we just need to find out where exactly:
248 // check whether to insert it as new first item
249 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
250 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
252 } // check whether to insert it as new last item
253 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
254 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
258 end = serverlist_viewcount - 1;
259 while( end > start + 1 )
261 mid = (start + end) / 2;
262 // test the item that lies in the middle between start and end
263 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
264 // the item has to be in the upper half
267 // the item has to be in the lower half
270 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
273 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
276 for( i = 0; i < serverlist_viewcount; i++ )
278 if (serverlist_viewlist[i] == entry)
280 _ServerList_ViewList_Helper_Remove(i);
286 void ServerList_RebuildViewList(void)
290 serverlist_viewcount = 0;
291 for( i = 0 ; i < serverlist_cachecount ; i++ )
292 if( serverlist_cache[i].finished )
293 ServerList_ViewList_Insert( &serverlist_cache[i] );
296 void ServerList_ResetMasks(void)
298 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
299 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
303 static void _ServerList_Test(void)
306 for( i = 0 ; i < 1024 ; i++ ) {
307 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_t ) );
308 serverlist_cache[serverlist_cachecount].info.ping = rand() % 450 + 250;
309 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, 128, "Black's ServerList Test %i", i );
310 serverlist_cache[serverlist_cachecount].finished = true;
311 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
312 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
313 serverlist_cachecount++;
318 void ServerList_QueryList(void)
320 masterquerytime = realtime;
321 masterquerycount = 0;
322 masterreplycount = 0;
323 serverquerycount = 0;
324 serverreplycount = 0;
325 serverlist_cachecount = 0;
326 serverlist_viewcount = 0;
327 serverlist_consoleoutput = false;
328 NetConn_QueryMasters();
330 //_ServerList_Test();
335 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
337 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
341 if (cl_netpacketloss.integer)
342 for (i = 0;i < cl_numsockets;i++)
343 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
345 if (developer_networking.integer)
347 char addressstring[128], addressstring2[128];
348 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
351 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
352 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
353 Com_HexDumpToConsole(data, length);
356 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
361 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
365 if (cl_netpacketloss.integer)
366 for (i = 0;i < cl_numsockets;i++)
367 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
369 ret = LHNET_Write(mysocket, data, length, peeraddress);
370 if (developer_networking.integer)
372 char addressstring[128], addressstring2[128];
373 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
374 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
375 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
376 Com_HexDumpToConsole(data, length);
381 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
383 // note this does not include the trailing NULL because we add that in the parser
384 return NetConn_Write(mysocket, string, strlen(string), peeraddress);
387 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
389 unsigned int packetLen;
390 unsigned int dataLen;
392 unsigned int *header;
395 if (data->cursize == 0)
396 Sys_Error("Datagram_SendMessage: zero length message\n");
398 if (data->cursize > (int)sizeof(conn->sendMessage))
399 Sys_Error("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
401 if (conn->canSend == false)
402 Sys_Error("SendMessage: called with canSend == false\n");
405 memcpy(conn->sendMessage, data->data, data->cursize);
406 conn->sendMessageLength = data->cursize;
408 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
410 dataLen = conn->sendMessageLength;
415 dataLen = MAX_PACKETFRAGMENT;
419 packetLen = NET_HEADERSIZE + dataLen;
421 header = (void *)sendbuffer;
422 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
423 header[1] = BigLong(conn->sendSequence);
424 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
426 conn->sendSequence++;
427 conn->canSend = false;
429 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
432 conn->lastSendTime = realtime;
434 reliableMessagesSent++;
438 static void NetConn_SendMessageNext(netconn_t *conn)
440 unsigned int packetLen;
441 unsigned int dataLen;
443 unsigned int *header;
445 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
447 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
449 dataLen = conn->sendMessageLength;
454 dataLen = MAX_PACKETFRAGMENT;
458 packetLen = NET_HEADERSIZE + dataLen;
460 header = (void *)sendbuffer;
461 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
462 header[1] = BigLong(conn->sendSequence);
463 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
465 conn->sendSequence++;
466 conn->sendNext = false;
468 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
471 conn->lastSendTime = realtime;
476 static void NetConn_ReSendMessage(netconn_t *conn)
478 unsigned int packetLen;
479 unsigned int dataLen;
481 unsigned int *header;
483 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
485 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
487 dataLen = conn->sendMessageLength;
492 dataLen = MAX_PACKETFRAGMENT;
496 packetLen = NET_HEADERSIZE + dataLen;
498 header = (void *)sendbuffer;
499 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
500 header[1] = BigLong(conn->sendSequence - 1);
501 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
503 conn->sendNext = false;
505 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
508 conn->lastSendTime = realtime;
513 qboolean NetConn_CanSendMessage(netconn_t *conn)
515 return conn->canSend;
518 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
523 packetLen = NET_HEADERSIZE + data->cursize;
526 if (data->cursize == 0)
527 Sys_Error("Datagram_SendUnreliableMessage: zero length message\n");
529 if (packetLen > (int)sizeof(sendbuffer))
530 Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
533 header = (void *)sendbuffer;
534 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
535 header[1] = BigLong(conn->unreliableSendSequence);
536 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
538 conn->unreliableSendSequence++;
540 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
544 unreliableMessagesSent++;
548 void NetConn_CloseClientPorts(void)
550 for (;cl_numsockets > 0;cl_numsockets--)
551 if (cl_sockets[cl_numsockets - 1])
552 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
555 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
557 lhnetaddress_t address;
559 char addressstring2[1024];
560 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
562 if ((s = LHNET_OpenSocket_Connectionless(&address)))
564 cl_sockets[cl_numsockets++] = s;
565 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
566 Con_Printf("Client opened a socket on address %s\n", addressstring2);
570 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
571 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
575 Con_Printf("Client unable to parse address %s\n", addressstring);
578 void NetConn_OpenClientPorts(void)
581 NetConn_CloseClientPorts();
582 port = bound(0, cl_netport.integer, 65535);
583 if (cl_netport.integer != port)
584 Cvar_SetValueQuick(&cl_netport, port);
585 Con_Printf("Client using port %i\n", port);
586 NetConn_OpenClientPort("local:2", 0);
587 NetConn_OpenClientPort(net_address.string, port);
588 //NetConn_OpenClientPort(net_address_ipv6.string, port);
591 void NetConn_CloseServerPorts(void)
593 for (;sv_numsockets > 0;sv_numsockets--)
594 if (sv_sockets[sv_numsockets - 1])
595 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
598 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
600 lhnetaddress_t address;
602 char addressstring2[1024];
603 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
605 if ((s = LHNET_OpenSocket_Connectionless(&address)))
607 sv_sockets[sv_numsockets++] = s;
608 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
609 Con_Printf("Server listening on address %s\n", addressstring2);
613 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
614 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
618 Con_Printf("Server unable to parse address %s\n", addressstring);
621 void NetConn_OpenServerPorts(int opennetports)
624 NetConn_CloseServerPorts();
625 port = bound(0, sv_netport.integer, 65535);
628 Con_Printf("Server using port %i\n", port);
629 if (sv_netport.integer != port)
630 Cvar_SetValueQuick(&sv_netport, port);
631 if (cls.state != ca_dedicated)
632 NetConn_OpenServerPort("local:1", 0);
635 NetConn_OpenServerPort(net_address.string, port);
636 //NetConn_OpenServerPort(net_address_ipv6.string, port);
638 if (sv_numsockets == 0)
639 Host_Error("NetConn_OpenServerPorts: unable to open any ports!\n");
642 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
644 int i, a = LHNETADDRESS_GetAddressType(address);
645 for (i = 0;i < cl_numsockets;i++)
646 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
647 return cl_sockets[i];
651 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
653 int i, a = LHNETADDRESS_GetAddressType(address);
654 for (i = 0;i < sv_numsockets;i++)
655 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
656 return sv_sockets[i];
660 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
663 conn = Mem_Alloc(netconn_mempool, sizeof(*conn));
664 conn->mysocket = mysocket;
665 conn->peeraddress = *peeraddress;
666 conn->canSend = true;
667 conn->lastMessageTime = realtime;
668 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
669 // reduce effectiveness of connection request floods
670 conn->timeout = realtime + net_connecttimeout.value;
671 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
672 conn->next = netconn_list;
677 void NetConn_Close(netconn_t *conn)
680 // remove connection from list
681 if (conn == netconn_list)
682 netconn_list = conn->next;
685 for (c = netconn_list;c;c = c->next)
689 c->next = conn->next;
693 // not found in list, we'll avoid crashing here...
701 static int clientport = -1;
702 static int clientport2 = -1;
703 static int hostport = -1;
704 static void NetConn_UpdateServerStuff(void)
706 if (cls.state != ca_dedicated)
708 if (clientport2 != cl_netport.integer)
710 clientport2 = cl_netport.integer;
711 if (cls.state == ca_connected)
712 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
714 if (cls.state == ca_disconnected && clientport != clientport2)
716 clientport = clientport2;
717 NetConn_CloseClientPorts();
719 if (cl_numsockets == 0)
720 NetConn_OpenClientPorts();
723 if (hostport != sv_netport.integer)
725 hostport = sv_netport.integer;
727 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
731 int NetConn_ReceivedMessage(netconn_t *conn, qbyte *data, int length)
735 unsigned int sequence;
739 length = BigLong(((int *)data)[0]);
740 flags = length & ~NETFLAG_LENGTH_MASK;
741 length &= NETFLAG_LENGTH_MASK;
742 // control packets were already handled
743 if (!(flags & NETFLAG_CTL))
745 sequence = BigLong(((int *)data)[1]);
749 if (flags & NETFLAG_UNRELIABLE)
751 if (sequence >= conn->unreliableReceiveSequence)
753 if (sequence > conn->unreliableReceiveSequence)
755 count = sequence - conn->unreliableReceiveSequence;
756 droppedDatagrams += count;
757 Con_DPrintf("Dropped %u datagram(s)\n", count);
759 conn->unreliableReceiveSequence = sequence + 1;
760 conn->lastMessageTime = realtime;
761 conn->timeout = realtime + net_messagetimeout.value;
762 unreliableMessagesReceived++;
765 SZ_Clear(&net_message);
766 SZ_Write(&net_message, data, length);
772 Con_DPrint("Got a stale datagram\n");
775 else if (flags & NETFLAG_ACK)
777 if (sequence == (conn->sendSequence - 1))
779 if (sequence == conn->ackSequence)
782 if (conn->ackSequence != conn->sendSequence)
783 Con_DPrint("ack sequencing error\n");
784 conn->lastMessageTime = realtime;
785 conn->timeout = realtime + net_messagetimeout.value;
786 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
787 if (conn->sendMessageLength > 0)
789 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
790 conn->sendNext = true;
791 NetConn_SendMessageNext(conn);
795 conn->sendMessageLength = 0;
796 conn->canSend = true;
800 Con_DPrint("Duplicate ACK received\n");
803 Con_DPrint("Stale ACK received\n");
806 else if (flags & NETFLAG_DATA)
808 unsigned int temppacket[2];
809 temppacket[0] = BigLong(8 | NETFLAG_ACK);
810 temppacket[1] = BigLong(sequence);
811 NetConn_Write(conn->mysocket, (qbyte *)temppacket, 8, &conn->peeraddress);
812 if (sequence == conn->receiveSequence)
814 conn->lastMessageTime = realtime;
815 conn->timeout = realtime + net_messagetimeout.value;
816 conn->receiveSequence++;
817 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
818 conn->receiveMessageLength += length;
819 if (flags & NETFLAG_EOM)
821 reliableMessagesReceived++;
822 length = conn->receiveMessageLength;
823 conn->receiveMessageLength = 0;
826 SZ_Clear(&net_message);
827 SZ_Write(&net_message, conn->receiveMessage, length);
834 receivedDuplicateCount++;
842 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
844 cls.connect_trying = false;
845 M_Update_Return_Reason("");
846 // the connection request succeeded, stop current connection and set up a new connection
848 cls.netcon = NetConn_Open(mysocket, peeraddress);
849 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
852 cls.demonum = -1; // not in the demo loop now
853 cls.state = ca_connected;
854 cls.signon = 0; // need all the signon messages before playing
858 int NetConn_IsLocalGame(void)
860 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
865 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
868 lhnetaddress_t svaddress;
870 char *string, addressstring2[128], cname[128], ipstring[32];
871 char stringbuf[16384];
873 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
875 // received a command string - strip off the packaging and put it
876 // into our string buffer with NULL termination
879 length = min(length, (int)sizeof(stringbuf) - 1);
880 memcpy(stringbuf, data, length);
881 stringbuf[length] = 0;
884 if (developer.integer)
886 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
887 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
888 Com_HexDumpToConsole(data, length);
891 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
893 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
894 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
895 M_Update_Return_Reason("Got challenge response");
896 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\challenge\\%s", string + 10), peeraddress);
899 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
901 M_Update_Return_Reason("Accepted");
902 NetConn_ConnectionEstablished(mysocket, peeraddress);
905 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
907 char rejectreason[32];
908 cls.connect_trying = false;
910 length = max(length - 7, (int)sizeof(rejectreason) - 1);
911 memcpy(rejectreason, string, length);
912 rejectreason[length] = 0;
913 M_Update_Return_Reason(rejectreason);
916 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
918 serverlist_info_t *info;
923 // serverlist only uses text addresses
924 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
925 // search the cache for this server and update it
926 for( n = 0; n < serverlist_cachecount; n++ )
927 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
929 if( n == serverlist_cachecount )
932 info = &serverlist_cache[n].info;
933 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
934 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
935 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
936 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
937 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
938 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
939 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
941 if (info->ping == 100000)
944 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
945 pingtime = bound(0, pingtime, 9999);
947 info->ping = pingtime;
949 // legacy/old stuff move it to the menu ASAP
951 // build description strings for the things users care about
952 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);
953 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);
954 // if ping is especially high, display it as such
957 // orange numbers (lower block)
958 for (i = 0;i < 5;i++)
959 if (serverlist_cache[n].line1[i] != ' ')
960 serverlist_cache[n].line1[i] += 128;
962 else if (pingtime >= 200)
964 // yellow numbers (in upper block)
965 for (i = 0;i < 5;i++)
966 if (serverlist_cache[n].line1[i] != ' ')
967 serverlist_cache[n].line1[i] -= 30;
969 // and finally, update the view set
970 if( serverlist_cache[n].finished )
971 ServerList_ViewList_Remove( &serverlist_cache[n] );
972 // else if not in the slist menu we should print the server to console (if wanted)
973 else if( serverlist_consoleoutput )
974 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
975 ServerList_ViewList_Insert( &serverlist_cache[n] );
976 serverlist_cache[n].finished = true;
980 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
982 // Extract the IP addresses
986 if (serverlist_consoleoutput)
987 Con_Print("received server list...\n");
988 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
994 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
995 if (developer.integer)
996 Con_Printf("Requesting info from server %s\n", ipstring);
997 // ignore the rest of the message if the serverlist is full
998 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1000 // also ignore it if we have already queried it (other master server response)
1001 for( n = 0 ; n < serverlist_cachecount ; n++ )
1002 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1004 if( n < serverlist_cachecount )
1007 LHNETADDRESS_FromString(&svaddress, ipstring, 0);
1008 NetConn_WriteString(mysocket, "\377\377\377\377getinfo", &svaddress);
1010 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1011 // store the data the engine cares about (address and ping)
1012 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1013 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1014 serverlist_cache[serverlist_cachecount].querytime = realtime;
1015 // if not in the slist menu we should print the server to console
1016 if (serverlist_consoleoutput)
1017 Con_Printf("querying %s\n", ipstring);
1019 ++serverlist_cachecount;
1021 // move on to next address in packet
1028 if (!strncmp(string, "ping", 4))
1030 if (developer.integer)
1031 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1032 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1035 if (!strncmp(string, "ack", 3))
1038 // we may not have liked the packet, but it was a command packet, so
1039 // we're done processing this packet now
1042 // netquake control packets, supported for compatibility only
1043 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1048 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1052 if (developer.integer)
1053 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1054 if (cls.connect_trying)
1056 lhnetaddress_t clientportaddress;
1057 clientportaddress = *peeraddress;
1060 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1063 LHNETADDRESS_SetPort(&clientportaddress, port);
1065 M_Update_Return_Reason("Accepted");
1066 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1070 if (developer.integer)
1071 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1072 cls.connect_trying = false;
1073 M_Update_Return_Reason(data);
1076 case CCREP_SERVER_INFO:
1077 if (developer.integer)
1078 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1079 if (cls.state != ca_dedicated)
1081 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1082 // string we just ignore it and keep the real address
1084 // serverlist only uses text addresses
1085 cname = UDP_AddrToString(readaddr);
1086 // search the cache for this server
1087 for (n = 0; n < hostCacheCount; n++)
1088 if (!strcmp(cname, serverlist[n].cname))
1091 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1094 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1095 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1096 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1097 serverlist[n].users = MSG_ReadByte();
1098 serverlist[n].maxusers = MSG_ReadByte();
1100 if (c != NET_PROTOCOL_VERSION)
1102 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1103 strcpy(serverlist[n].name, "*");
1104 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1106 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1110 case CCREP_PLAYER_INFO:
1111 // we got a CCREP_PLAYER_INFO??
1112 //if (developer.integer)
1113 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1115 case CCREP_RULE_INFO:
1116 // we got a CCREP_RULE_INFO??
1117 //if (developer.integer)
1118 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1124 // we may not have liked the packet, but it was a valid control
1125 // packet, so we're done processing this packet now
1129 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)
1130 CL_ParseServerMessage();
1134 void NetConn_ClientFrame(void)
1137 lhnetaddress_t peeraddress;
1139 NetConn_UpdateServerStuff();
1140 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1142 if (cls.connect_remainingtries == 0)
1144 cls.connect_trying = false;
1145 M_Update_Return_Reason("Connect: Failed");
1148 cls.connect_nextsendtime = realtime + 1;
1149 cls.connect_remainingtries--;
1150 // try challenge first (newer server)
1151 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1152 // then try netquake as a fallback (old server, or netquake)
1153 SZ_Clear(&net_message);
1154 // save space for the header, filled in later
1155 MSG_WriteLong(&net_message, 0);
1156 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1157 MSG_WriteString(&net_message, "QUAKE");
1158 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1159 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1160 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1161 SZ_Clear(&net_message);
1163 for (i = 0;i < cl_numsockets;i++)
1164 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1165 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1166 if (cls.netcon && realtime > cls.netcon->timeout)
1168 Con_Print("Connection timed out\n");
1170 Host_ShutdownServer (false);
1172 for (conn = netconn_list;conn;conn = conn->next)
1173 NetConn_ReSendMessage(conn);
1176 #define MAX_CHALLENGES 128
1179 lhnetaddress_t address;
1183 challenge[MAX_CHALLENGES];
1185 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1189 for (i = 0;i < bufferlength - 1;i++)
1193 c = rand () % (127 - 33) + 33;
1194 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1200 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, qbyte *data, int length, lhnetaddress_t *peeraddress)
1202 int i, n, ret, clientnum, responselength, best;
1206 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1210 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1212 // received a command string - strip off the packaging and put it
1213 // into our string buffer with NULL termination
1216 length = min(length, (int)sizeof(stringbuf) - 1);
1217 memcpy(stringbuf, data, length);
1218 stringbuf[length] = 0;
1221 if (developer.integer)
1223 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1224 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1225 Com_HexDumpToConsole(data, length);
1228 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1230 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1232 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1234 if (besttime > challenge[i].time)
1235 besttime = challenge[best = i].time;
1237 // if we did not find an exact match, choose the oldest and
1238 // update address and string
1239 if (i == MAX_CHALLENGES)
1242 challenge[i].address = *peeraddress;
1243 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1245 challenge[i].time = realtime;
1246 // send the challenge
1247 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1250 if (length > 8 && !memcmp(string, "connect\\", 8))
1254 if ((s = SearchInfostring(string, "challenge")))
1256 // validate the challenge
1257 for (i = 0;i < MAX_CHALLENGES;i++)
1258 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1260 if (i < MAX_CHALLENGES)
1262 // check engine protocol
1263 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1265 if (developer.integer)
1266 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1267 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1271 // see if this is a duplicate connection request
1272 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1273 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1275 if (clientnum < svs.maxclients)
1277 // duplicate connection request
1278 if (realtime - client->connecttime < 2.0)
1280 // client is still trying to connect,
1281 // so we send a duplicate reply
1282 if (developer.integer)
1283 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1284 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1286 // only kick if old connection seems dead
1287 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1289 // kick off connection and await retry
1290 client->deadsocket = true;
1295 // this is a new client, find a slot
1296 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1297 if (!client->active)
1299 if (clientnum < svs.maxclients)
1301 // prepare the client struct
1302 if ((conn = NetConn_Open(mysocket, peeraddress)))
1304 // allocated connection
1305 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1306 if (developer.integer)
1307 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1308 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1309 // now set up the client
1310 SV_ConnectClient(clientnum, conn);
1311 NetConn_Heartbeat(1);
1317 if (developer.integer)
1318 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1319 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1327 if (length >= 7 && !memcmp(string, "getinfo", 7))
1329 const char *challenge = NULL;
1330 // If there was a challenge in the getinfo message
1331 if (length > 8 && string[7] == ' ')
1332 challenge = string + 8;
1333 for (i = 0, n = 0;i < svs.maxclients;i++)
1334 if (svs.clients[i].active)
1336 responselength = dpsnprintf(response, sizeof(response), "\377\377\377\377infoResponse\x0A"
1337 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1338 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d%s%s",
1339 gamename, com_modname, svs.maxclients, n,
1340 sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "");
1341 // does it fit in the buffer?
1342 if (responselength >= 0)
1344 if (developer.integer)
1345 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1346 NetConn_WriteString(mysocket, response, peeraddress);
1351 if (!strncmp(string, "ping", 4))
1353 if (developer.integer)
1354 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1355 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1358 if (!strncmp(string, "ack", 3))
1361 // we may not have liked the packet, but it was a command packet, so
1362 // we're done processing this packet now
1365 // LordHavoc: disabled netquake control packet support in server
1369 // netquake control packets, supported for compatibility only
1370 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1375 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1379 //if (developer.integer)
1380 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1381 if (length >= (int)strlen("QUAKE") + 1 + 1)
1383 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1385 if (developer.integer)
1386 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1387 SZ_Clear(&net_message);
1388 // save space for the header, filled in later
1389 MSG_WriteLong(&net_message, 0);
1390 MSG_WriteByte(&net_message, CCREP_REJECT);
1391 MSG_WriteString(&net_message, "Incompatible version.\n");
1392 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1393 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1394 SZ_Clear(&net_message);
1398 // see if this is a duplicate connection request
1399 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1400 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1402 if (clientnum < svs.maxclients)
1404 // duplicate connection request
1405 if (realtime - client->connecttime < 2.0)
1407 // client is still trying to connect,
1408 // so we send a duplicate reply
1409 if (developer.integer)
1410 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1411 SZ_Clear(&net_message);
1412 // save space for the header, filled in later
1413 MSG_WriteLong(&net_message, 0);
1414 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1415 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1416 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1417 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1418 SZ_Clear(&net_message);
1420 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1422 // the old client hasn't sent us anything
1423 // in quite a while, so kick off and let
1424 // the retry take care of it...
1425 client->deadsocket = true;
1430 // this is a new client, find a slot
1431 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1432 if (!client->active)
1434 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1436 // connect to the client
1437 // everything is allocated, just fill in the details
1438 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1439 if (developer.integer)
1440 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1441 // send back the info about the server connection
1442 SZ_Clear(&net_message);
1443 // save space for the header, filled in later
1444 MSG_WriteLong(&net_message, 0);
1445 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1446 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1447 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1448 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1449 SZ_Clear(&net_message);
1450 // now set up the client struct
1451 SV_ConnectClient(clientnum, conn);
1452 NetConn_Heartbeat(1);
1456 //if (developer.integer)
1457 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1458 // no room; try to let player know
1459 SZ_Clear(&net_message);
1460 // save space for the header, filled in later
1461 MSG_WriteLong(&net_message, 0);
1462 MSG_WriteByte(&net_message, CCREP_REJECT);
1463 MSG_WriteString(&net_message, "Server is full.\n");
1464 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1465 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1466 SZ_Clear(&net_message);
1473 case CCREQ_SERVER_INFO:
1474 if (developer.integer)
1475 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1476 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1478 if (developer.integer)
1479 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1480 SZ_Clear(&net_message);
1481 // save space for the header, filled in later
1482 MSG_WriteLong(&net_message, 0);
1483 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1484 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1485 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1486 MSG_WriteString(&net_message, hostname.string);
1487 MSG_WriteString(&net_message, sv.name);
1488 MSG_WriteByte(&net_message, net_activeconnections);
1489 MSG_WriteByte(&net_message, svs.maxclients);
1490 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1491 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1492 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1493 SZ_Clear(&net_message);
1496 case CCREQ_PLAYER_INFO:
1497 if (developer.integer)
1498 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1501 int playerNumber, activeNumber, clientNumber;
1504 playerNumber = MSG_ReadByte();
1506 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1507 if (client->active && ++activeNumber == playerNumber)
1509 if (clientNumber != svs.maxclients)
1511 SZ_Clear(&net_message);
1512 // save space for the header, filled in later
1513 MSG_WriteLong(&net_message, 0);
1514 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1515 MSG_WriteByte(&net_message, playerNumber);
1516 MSG_WriteString(&net_message, client->name);
1517 MSG_WriteLong(&net_message, client->colors);
1518 MSG_WriteLong(&net_message, (int)client->edict->v->frags);
1519 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1520 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1521 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1522 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1523 SZ_Clear(&net_message);
1527 case CCREQ_RULE_INFO:
1528 if (developer.integer)
1529 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1535 // find the search start location
1536 prevCvarName = MSG_ReadString();
1537 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1539 // send the response
1540 SZ_Clear(&net_message);
1541 // save space for the header, filled in later
1542 MSG_WriteLong(&net_message, 0);
1543 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1546 MSG_WriteString(&net_message, var->name);
1547 MSG_WriteString(&net_message, var->string);
1549 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1550 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1551 SZ_Clear(&net_message);
1558 // we may not have liked the packet, but it was a valid control
1559 // packet, so we're done processing this packet now
1564 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1566 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1568 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1569 SV_ReadClientMessage();
1577 void NetConn_ServerFrame(void)
1580 lhnetaddress_t peeraddress;
1582 NetConn_UpdateServerStuff();
1583 for (i = 0;i < sv_numsockets;i++)
1584 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1585 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1586 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1588 // never timeout loopback connections
1589 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1591 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1592 SV_DropClient(false);
1595 for (conn = netconn_list;conn;conn = conn->next)
1596 NetConn_ReSendMessage(conn);
1599 void NetConn_QueryMasters(void)
1603 lhnetaddress_t masteraddress;
1604 lhnetaddress_t broadcastaddress;
1607 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1610 // 26000 is the default quake server port, servers on other ports will not
1612 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1613 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1615 for (i = 0;i < cl_numsockets;i++)
1619 // search LAN for Quake servers
1620 SZ_Clear(&net_message);
1621 // save space for the header, filled in later
1622 MSG_WriteLong(&net_message, 0);
1623 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1624 MSG_WriteString(&net_message, "QUAKE");
1625 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1626 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1627 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1628 SZ_Clear(&net_message);
1630 // search LAN for DarkPlaces servers
1631 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1633 // build the getservers message to send to the master servers
1634 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1637 for (masternum = 0;sv_masters[masternum].name;masternum++)
1639 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1642 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1647 if (!masterquerycount)
1649 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1650 M_Update_Return_Reason("No network");
1654 void NetConn_Heartbeat(int priority)
1656 lhnetaddress_t masteraddress;
1658 lhnetsocket_t *mysocket;
1660 // if it's a state change (client connected), limit next heartbeat to no
1661 // more than 30 sec in the future
1662 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1663 nextheartbeattime = realtime + 30.0;
1665 // limit heartbeatperiod to 30 to 270 second range,
1666 // lower limit is to avoid abusing master servers with excess traffic,
1667 // upper limit is to avoid timing out on the master server (which uses
1669 if (sv_heartbeatperiod.value < 30)
1670 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1671 if (sv_heartbeatperiod.value > 270)
1672 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1674 // make advertising optional and don't advertise singleplayer games, and
1675 // only send a heartbeat as often as the admin wants
1676 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1678 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1679 for (masternum = 0;sv_masters[masternum].name;masternum++)
1680 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1681 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1685 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1688 qbyte sent[MAX_SCOREBOARD];
1690 memset(sent, 0, sizeof(sent));
1692 // simultaneously wait for the first CanSendMessage and send the message,
1693 // then wait for a second CanSendMessage (verifying it was received), or
1694 // the client drops and is no longer counted
1695 // the loop aborts when either it runs out of clients to send to, or a
1697 blocktime += Sys_DoubleTime();
1701 NetConn_ClientFrame();
1702 NetConn_ServerFrame();
1703 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1705 if (host_client->netconnection)
1707 if (NetConn_CanSendMessage(host_client->netconnection))
1710 NetConn_SendReliableMessage(host_client->netconnection, data);
1713 if (!NetConn_CanSendMessage(host_client->netconnection))
1718 while (count && Sys_DoubleTime() < blocktime);
1722 static void Net_Heartbeat_f(void)
1725 NetConn_Heartbeat(2);
1727 Con_Print("No server running, can not heartbeat to master server.\n");
1730 void PrintStats(netconn_t *conn)
1732 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1735 void Net_Stats_f(void)
1738 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1739 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1740 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1741 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1742 Con_Printf("packetsSent = %i\n", packetsSent);
1743 Con_Printf("packetsReSent = %i\n", packetsReSent);
1744 Con_Printf("packetsReceived = %i\n", packetsReceived);
1745 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1746 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1747 Con_Print("connections =\n");
1748 for (conn = netconn_list;conn;conn = conn->next)
1752 void Net_Slist_f(void)
1754 ServerList_ResetMasks();
1755 serverlist_sortbyfield = SLIF_PING;
1756 serverlist_sortdescending = false;
1757 if (m_state != m_slist) {
1758 Con_Print("Sending requests to master servers\n");
1759 ServerList_QueryList();
1760 serverlist_consoleoutput = true;
1761 Con_Print("Listening for replies...\n");
1763 ServerList_QueryList();
1766 void NetConn_Init(void)
1769 lhnetaddress_t tempaddress;
1770 netconn_mempool = Mem_AllocPool("Networking", 0, NULL);
1771 Cmd_AddCommand("net_stats", Net_Stats_f);
1772 Cmd_AddCommand("net_slist", Net_Slist_f);
1773 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
1774 Cvar_RegisterVariable(&net_messagetimeout);
1775 Cvar_RegisterVariable(&net_messagerejointimeout);
1776 Cvar_RegisterVariable(&net_connecttimeout);
1777 Cvar_RegisterVariable(&cl_netlocalping);
1778 Cvar_RegisterVariable(&cl_netpacketloss);
1779 Cvar_RegisterVariable(&hostname);
1780 Cvar_RegisterVariable(&developer_networking);
1781 Cvar_RegisterVariable(&cl_netport);
1782 Cvar_RegisterVariable(&sv_netport);
1783 Cvar_RegisterVariable(&net_address);
1784 //Cvar_RegisterVariable(&net_address_ipv6);
1785 Cvar_RegisterVariable(&sv_public);
1786 Cvar_RegisterVariable(&sv_heartbeatperiod);
1787 for (i = 0;sv_masters[i].name;i++)
1788 Cvar_RegisterVariable(&sv_masters[i]);
1789 // 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.
1790 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
1792 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
1794 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
1795 Cvar_SetQuick(&net_address, com_argv[i + 1]);
1798 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
1800 // 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
1801 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
1803 i = atoi(com_argv[i + 1]);
1804 if (i >= 0 && i < 65536)
1806 Con_Printf("-port option used, setting port cvar to %i\n", i);
1807 Cvar_SetValueQuick(&sv_netport, i);
1810 Con_Printf("-port option used, but %i is not a valid port number\n", i);
1814 SZ_Alloc(&net_message, NET_MAXMESSAGE, "net_message");
1818 void NetConn_Shutdown(void)
1820 NetConn_CloseClientPorts();
1821 NetConn_CloseServerPorts();