2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define MASTER_PORT 27950
28 // note this defaults on for dedicated servers, off for listen servers
29 cvar_t sv_public = {0, "sv_public", "0"};
30 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120"};
32 // FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat)
33 static cvar_t sv_masters [] =
35 {CVAR_SAVE, "sv_master1", ""},
36 {CVAR_SAVE, "sv_master2", ""},
37 {CVAR_SAVE, "sv_master3", ""},
38 {CVAR_SAVE, "sv_master4", ""},
39 {0, "sv_masterextra1", "ghdigital.com"}, // admin: LordHavoc
40 {0, "sv_masterextra2", "dpmaster.deathmask.net"}, // admin: Willis
41 {0, "sv_masterextra3", "12.166.196.192"}, // admin: Venim
42 {0, "sv_masterextra4", "excalibur.nvg.ntnu.no"}, // admin: tChr
46 static double nextheartbeattime = 0;
48 sizebuf_t net_message;
49 static unsigned char net_message_buf[NET_MAXMESSAGE];
51 cvar_t net_messagetimeout = {0, "net_messagetimeout","300"};
52 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10"};
53 cvar_t net_connecttimeout = {0, "net_connecttimeout","10"};
54 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED"};
55 cvar_t developer_networking = {0, "developer_networking", "0"};
57 cvar_t cl_netlocalping = {0, "cl_netlocalping","0"};
58 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0"};
59 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20"};
60 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4"};
61 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4"};
62 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3"};
64 /* statistic counters */
65 static int packetsSent = 0;
66 static int packetsReSent = 0;
67 static int packetsReceived = 0;
68 static int receivedDuplicateCount = 0;
69 static int droppedDatagrams = 0;
71 static int unreliableMessagesSent = 0;
72 static int unreliableMessagesReceived = 0;
73 static int reliableMessagesSent = 0;
74 static int reliableMessagesReceived = 0;
76 double masterquerytime = -1000;
77 int masterquerycount = 0;
78 int masterreplycount = 0;
79 int serverquerycount = 0;
80 int serverreplycount = 0;
82 // this is only false if there are still servers left to query
83 int serverlist_querysleep = true;
85 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
86 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
89 lhnetsocket_t *cl_sockets[16];
91 lhnetsocket_t *sv_sockets[16];
93 netconn_t *netconn_list = NULL;
94 mempool_t *netconn_mempool = NULL;
96 cvar_t cl_netport = {0, "cl_port", "0"};
97 cvar_t sv_netport = {0, "port", "26000"};
98 cvar_t net_address = {0, "net_address", "0.0.0.0"};
99 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]"};
101 // ServerList interface
102 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
103 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
105 serverlist_infofield_t serverlist_sortbyfield;
106 qboolean serverlist_sortdescending;
108 int serverlist_viewcount = 0;
109 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
111 int serverlist_cachecount;
112 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
114 qboolean serverlist_consoleoutput;
116 // helper function to insert a value into the viewset
117 // spare entries will be removed
118 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
121 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
122 i = serverlist_viewcount++;
124 i = SERVERLIST_VIEWLISTSIZE - 1;
127 for( ; i > index ; i-- )
128 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
130 serverlist_viewlist[index] = entry;
133 // we suppose serverlist_viewcount to be valid, ie > 0
134 static void _ServerList_ViewList_Helper_Remove( int index )
136 serverlist_viewcount--;
137 for( ; index < serverlist_viewcount ; index++ )
138 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
141 // returns true if A should be inserted before B
142 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
144 int result = 0; // > 0 if for numbers A > B and for text if A < B
146 switch( serverlist_sortbyfield ) {
148 result = A->info.ping - B->info.ping;
150 case SLIF_MAXPLAYERS:
151 result = A->info.maxplayers - B->info.maxplayers;
153 case SLIF_NUMPLAYERS:
154 result = A->info.numplayers - B->info.numplayers;
157 result = A->info.protocol - B->info.protocol;
160 result = strcmp( B->info.cname, A->info.cname );
163 result = strcmp( B->info.game, A->info.game );
166 result = strcmp( B->info.map, A->info.map );
169 result = strcmp( B->info.mod, A->info.mod );
172 result = strcmp( B->info.name, A->info.name );
175 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
179 if( serverlist_sortdescending )
184 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
186 // This should actually be done with some intermediate and end-of-function return
198 case SLMO_GREATEREQUAL:
200 case SLMO_NOTCONTAIN:
203 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
208 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
211 char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
212 for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
213 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
215 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
216 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
219 // Same here, also using an intermediate & final return would be more appropriate
223 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
224 case SLMO_NOTCONTAIN:
225 return !*bufferB || !strstr( bufferA, bufferB );
227 return strcmp( bufferA, bufferB ) < 0;
229 return strcmp( bufferA, bufferB ) <= 0;
231 return strcmp( bufferA, bufferB ) == 0;
233 return strcmp( bufferA, bufferB ) > 0;
235 return strcmp( bufferA, bufferB ) != 0;
236 case SLMO_GREATEREQUAL:
237 return strcmp( bufferA, bufferB ) >= 0;
239 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
244 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
246 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
248 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
250 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
252 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
254 if( *mask->info.cname
255 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
258 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
261 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
264 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
267 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
272 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
276 // FIXME: change this to be more readable (...)
277 // now check whether it passes through the masks
278 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
279 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
282 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
283 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
285 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
288 if( !serverlist_viewcount ) {
289 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
292 // ok, insert it, we just need to find out where exactly:
295 // check whether to insert it as new first item
296 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
297 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
299 } // check whether to insert it as new last item
300 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
301 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
305 end = serverlist_viewcount - 1;
306 while( end > start + 1 )
308 mid = (start + end) / 2;
309 // test the item that lies in the middle between start and end
310 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
311 // the item has to be in the upper half
314 // the item has to be in the lower half
317 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
320 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
323 for( i = 0; i < serverlist_viewcount; i++ )
325 if (serverlist_viewlist[i] == entry)
327 _ServerList_ViewList_Helper_Remove(i);
333 void ServerList_RebuildViewList(void)
337 serverlist_viewcount = 0;
338 for( i = 0 ; i < serverlist_cachecount ; i++ )
339 if( serverlist_cache[i].query == SQS_QUERIED )
340 ServerList_ViewList_Insert( &serverlist_cache[i] );
343 void ServerList_ResetMasks(void)
345 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
346 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
350 static void _ServerList_Test(void)
353 for( i = 0 ; i < 1024 ; i++ ) {
354 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
355 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
356 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
357 serverlist_cache[serverlist_cachecount].finished = true;
358 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
359 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
360 serverlist_cachecount++;
365 void ServerList_QueryList(void)
367 masterquerytime = realtime;
368 masterquerycount = 0;
369 masterreplycount = 0;
370 serverquerycount = 0;
371 serverreplycount = 0;
372 serverlist_cachecount = 0;
373 serverlist_viewcount = 0;
374 serverlist_consoleoutput = false;
376 //_ServerList_Test();
378 NetConn_QueryMasters();
383 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
385 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
389 if (cl_netpacketloss.integer)
390 for (i = 0;i < cl_numsockets;i++)
391 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
393 if (developer_networking.integer)
395 char addressstring[128], addressstring2[128];
396 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
399 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
400 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
401 Com_HexDumpToConsole((unsigned char *)data, length);
404 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
409 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
413 if (cl_netpacketloss.integer)
414 for (i = 0;i < cl_numsockets;i++)
415 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
417 ret = LHNET_Write(mysocket, data, length, peeraddress);
418 if (developer_networking.integer)
420 char addressstring[128], addressstring2[128];
421 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
422 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
423 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
424 Com_HexDumpToConsole((unsigned char *)data, length);
429 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
431 // note this does not include the trailing NULL because we add that in the parser
432 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
435 int NetConn_SendReliableMessage(netconn_t *conn, sizebuf_t *data)
437 unsigned int packetLen;
438 unsigned int dataLen;
440 unsigned int *header;
443 if (data->cursize == 0)
445 Con_Printf ("Datagram_SendMessage: zero length message\n");
449 if (data->cursize > (int)sizeof(conn->sendMessage))
451 Con_Printf ("Datagram_SendMessage: message too big (%u > %u)\n", data->cursize, sizeof(conn->sendMessage));
455 if (conn->canSend == false)
457 Con_Printf ("SendMessage: called with canSend == false\n");
462 memcpy(conn->sendMessage, data->data, data->cursize);
463 conn->sendMessageLength = data->cursize;
465 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
467 dataLen = conn->sendMessageLength;
472 dataLen = MAX_PACKETFRAGMENT;
476 packetLen = NET_HEADERSIZE + dataLen;
478 header = (unsigned int *)sendbuffer;
479 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
480 header[1] = BigLong(conn->sendSequence);
481 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
483 conn->sendSequence++;
484 conn->canSend = false;
486 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
489 conn->lastSendTime = realtime;
491 reliableMessagesSent++;
495 static void NetConn_SendMessageNext(netconn_t *conn)
497 unsigned int packetLen;
498 unsigned int dataLen;
500 unsigned int *header;
502 if (conn->sendMessageLength && !conn->canSend && conn->sendNext)
504 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
506 dataLen = conn->sendMessageLength;
511 dataLen = MAX_PACKETFRAGMENT;
515 packetLen = NET_HEADERSIZE + dataLen;
517 header = (unsigned int *)sendbuffer;
518 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
519 header[1] = BigLong(conn->sendSequence);
520 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
522 conn->sendSequence++;
523 conn->sendNext = false;
525 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
528 conn->lastSendTime = realtime;
533 static void NetConn_ReSendMessage(netconn_t *conn)
535 unsigned int packetLen;
536 unsigned int dataLen;
538 unsigned int *header;
540 if (conn->sendMessageLength && !conn->canSend && (realtime - conn->lastSendTime) > 1.0)
542 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
544 dataLen = conn->sendMessageLength;
549 dataLen = MAX_PACKETFRAGMENT;
553 packetLen = NET_HEADERSIZE + dataLen;
555 header = (unsigned int *)sendbuffer;
556 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
557 header[1] = BigLong(conn->sendSequence - 1);
558 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
560 conn->sendNext = false;
562 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
565 conn->lastSendTime = realtime;
570 qboolean NetConn_CanSendMessage(netconn_t *conn)
572 return conn->canSend;
575 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data)
578 unsigned int *header;
580 packetLen = NET_HEADERSIZE + data->cursize;
583 if (data->cursize == 0)
585 Con_Printf ("Datagram_SendUnreliableMessage: zero length message\n");
589 if (packetLen > (int)sizeof(sendbuffer))
591 Con_Printf ("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize);
596 header = (unsigned int *)sendbuffer;
597 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
598 header[1] = BigLong(conn->unreliableSendSequence);
599 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
601 conn->unreliableSendSequence++;
603 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) != (int)packetLen)
607 unreliableMessagesSent++;
611 void NetConn_CloseClientPorts(void)
613 for (;cl_numsockets > 0;cl_numsockets--)
614 if (cl_sockets[cl_numsockets - 1])
615 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
618 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
620 lhnetaddress_t address;
622 char addressstring2[1024];
623 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
625 if ((s = LHNET_OpenSocket_Connectionless(&address)))
627 cl_sockets[cl_numsockets++] = s;
628 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
629 Con_Printf("Client opened a socket on address %s\n", addressstring2);
633 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
634 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
638 Con_Printf("Client unable to parse address %s\n", addressstring);
641 void NetConn_OpenClientPorts(void)
644 NetConn_CloseClientPorts();
645 port = bound(0, cl_netport.integer, 65535);
646 if (cl_netport.integer != port)
647 Cvar_SetValueQuick(&cl_netport, port);
648 Con_Printf("Client using port %i\n", port);
649 NetConn_OpenClientPort("local:2", 0);
650 NetConn_OpenClientPort(net_address.string, port);
651 //NetConn_OpenClientPort(net_address_ipv6.string, port);
654 void NetConn_CloseServerPorts(void)
656 for (;sv_numsockets > 0;sv_numsockets--)
657 if (sv_sockets[sv_numsockets - 1])
658 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
661 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
663 lhnetaddress_t address;
666 char addressstring2[1024];
668 for (port = defaultport; port <= defaultport + 100; port++)
670 if (LHNETADDRESS_FromString(&address, addressstring, port))
672 if ((s = LHNET_OpenSocket_Connectionless(&address)))
674 sv_sockets[sv_numsockets++] = s;
675 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
676 Con_Printf("Server listening on address %s\n", addressstring2);
681 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
682 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
687 Con_Printf("Server unable to parse address %s\n", addressstring);
688 // if it cant parse one address, it wont be able to parse another for sure
694 static void NetConn_UpdateServerStuff(void);
695 void NetConn_OpenServerPorts(int opennetports)
698 NetConn_CloseServerPorts();
699 NetConn_UpdateServerStuff();
700 port = bound(0, sv_netport.integer, 65535);
703 Con_Printf("Server using port %i\n", port);
704 if (sv_netport.integer != port)
705 Cvar_SetValueQuick(&sv_netport, port);
706 if (cls.state != ca_dedicated)
707 NetConn_OpenServerPort("local:1", 0);
710 NetConn_OpenServerPort(net_address.string, port);
711 //NetConn_OpenServerPort(net_address_ipv6.string, port);
713 if (sv_numsockets == 0)
714 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
717 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
719 int i, a = LHNETADDRESS_GetAddressType(address);
720 for (i = 0;i < cl_numsockets;i++)
721 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
722 return cl_sockets[i];
726 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
728 int i, a = LHNETADDRESS_GetAddressType(address);
729 for (i = 0;i < sv_numsockets;i++)
730 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
731 return sv_sockets[i];
735 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
738 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
739 conn->mysocket = mysocket;
740 conn->peeraddress = *peeraddress;
741 conn->canSend = true;
742 conn->lastMessageTime = realtime;
743 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
744 // reduce effectiveness of connection request floods
745 conn->timeout = realtime + net_connecttimeout.value;
746 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
747 conn->next = netconn_list;
752 void NetConn_Close(netconn_t *conn)
755 // remove connection from list
756 if (conn == netconn_list)
757 netconn_list = conn->next;
760 for (c = netconn_list;c;c = c->next)
764 c->next = conn->next;
768 // not found in list, we'll avoid crashing here...
776 static int clientport = -1;
777 static int clientport2 = -1;
778 static int hostport = -1;
779 static void NetConn_UpdateServerStuff(void)
781 if (cls.state != ca_dedicated)
783 if (clientport2 != cl_netport.integer)
785 clientport2 = cl_netport.integer;
786 if (cls.state == ca_connected)
787 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
789 if (cls.state == ca_disconnected && clientport != clientport2)
791 clientport = clientport2;
792 NetConn_CloseClientPorts();
794 if (cl_numsockets == 0)
795 NetConn_OpenClientPorts();
798 if (hostport != sv_netport.integer)
800 hostport = sv_netport.integer;
802 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
806 int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length)
810 unsigned int sequence;
815 qlength = (unsigned int)BigLong(((int *)data)[0]);
816 flags = qlength & ~NETFLAG_LENGTH_MASK;
817 qlength &= NETFLAG_LENGTH_MASK;
818 // control packets were already handled
819 if (!(flags & NETFLAG_CTL) && qlength == length)
821 sequence = BigLong(((int *)data)[1]);
825 if (flags & NETFLAG_UNRELIABLE)
827 if (sequence >= conn->unreliableReceiveSequence)
829 if (sequence > conn->unreliableReceiveSequence)
831 count = sequence - conn->unreliableReceiveSequence;
832 droppedDatagrams += count;
833 Con_DPrintf("Dropped %u datagram(s)\n", count);
835 conn->unreliableReceiveSequence = sequence + 1;
836 conn->lastMessageTime = realtime;
837 conn->timeout = realtime + net_messagetimeout.value;
838 unreliableMessagesReceived++;
841 SZ_Clear(&net_message);
842 SZ_Write(&net_message, data, length);
848 Con_DPrint("Got a stale datagram\n");
851 else if (flags & NETFLAG_ACK)
853 if (sequence == (conn->sendSequence - 1))
855 if (sequence == conn->ackSequence)
858 if (conn->ackSequence != conn->sendSequence)
859 Con_DPrint("ack sequencing error\n");
860 conn->lastMessageTime = realtime;
861 conn->timeout = realtime + net_messagetimeout.value;
862 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
863 if (conn->sendMessageLength > 0)
865 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
866 conn->sendNext = true;
867 NetConn_SendMessageNext(conn);
871 conn->sendMessageLength = 0;
872 conn->canSend = true;
876 Con_DPrint("Duplicate ACK received\n");
879 Con_DPrint("Stale ACK received\n");
882 else if (flags & NETFLAG_DATA)
884 unsigned int temppacket[2];
885 temppacket[0] = BigLong(8 | NETFLAG_ACK);
886 temppacket[1] = BigLong(sequence);
887 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
888 if (sequence == conn->receiveSequence)
890 conn->lastMessageTime = realtime;
891 conn->timeout = realtime + net_messagetimeout.value;
892 conn->receiveSequence++;
893 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
894 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
895 conn->receiveMessageLength += length;
897 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
898 "Dropping the message!\n", sequence );
899 conn->receiveMessageLength = 0;
902 if (flags & NETFLAG_EOM)
904 reliableMessagesReceived++;
905 length = conn->receiveMessageLength;
906 conn->receiveMessageLength = 0;
909 SZ_Clear(&net_message);
910 SZ_Write(&net_message, conn->receiveMessage, length);
917 receivedDuplicateCount++;
925 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
927 cls.connect_trying = false;
928 M_Update_Return_Reason("");
929 // the connection request succeeded, stop current connection and set up a new connection
931 // if we're connecting to a remote server, shut down any local server
932 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
933 Host_ShutdownServer (false);
934 // allocate a net connection to keep track of things
935 cls.netcon = NetConn_Open(mysocket, peeraddress);
936 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
939 cls.demonum = -1; // not in the demo loop now
940 cls.state = ca_connected;
941 cls.signon = 0; // need all the signon messages before playing
944 int NetConn_IsLocalGame(void)
946 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
951 int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
955 char *string, addressstring2[128], cname[128], ipstring[32];
956 char stringbuf[16384];
958 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
960 // received a command string - strip off the packaging and put it
961 // into our string buffer with NULL termination
964 length = min(length, (int)sizeof(stringbuf) - 1);
965 memcpy(stringbuf, data, length);
966 stringbuf[length] = 0;
969 if (developer.integer)
971 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
972 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
973 Com_HexDumpToConsole(data, length);
976 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
978 char protocolnames[1400];
979 Protocol_Names(protocolnames, sizeof(protocolnames));
980 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
981 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
982 M_Update_Return_Reason("Got challenge response");
983 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
986 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
988 M_Update_Return_Reason("Accepted");
989 NetConn_ConnectionEstablished(mysocket, peeraddress);
992 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
994 char rejectreason[32];
995 cls.connect_trying = false;
997 length = max(length - 7, (int)sizeof(rejectreason) - 1);
998 memcpy(rejectreason, string, length);
999 rejectreason[length] = 0;
1000 M_Update_Return_Reason(rejectreason);
1003 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1005 serverlist_info_t *info;
1010 // serverlist only uses text addresses
1011 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
1012 // search the cache for this server and update it
1013 for( n = 0; n < serverlist_cachecount; n++ )
1014 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
1016 if( n == serverlist_cachecount ) {
1017 // LAN search doesnt require an answer from the master server so we wont
1018 // know the ping nor will it be initialized already...
1021 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1024 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1025 // store the data the engine cares about (address and ping)
1026 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1027 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1028 serverlist_cache[serverlist_cachecount].querytime = realtime;
1029 // if not in the slist menu we should print the server to console
1030 if (serverlist_consoleoutput) {
1031 Con_Printf("querying %s\n", ipstring);
1034 ++serverlist_cachecount;
1037 info = &serverlist_cache[n].info;
1038 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1039 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1040 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1041 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1042 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1043 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1044 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1046 if (info->ping == 100000)
1049 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1050 pingtime = bound(0, pingtime, 9999);
1052 info->ping = pingtime;
1054 // legacy/old stuff move it to the menu ASAP
1056 // build description strings for the things users care about
1057 dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "%c%c%5d%c%c%c%3u/%3u %-65.65s", STRING_COLOR_TAG, pingtime >= 300 ? '1' : (pingtime >= 200 ? '3' : '7'), (int)pingtime, STRING_COLOR_TAG, STRING_COLOR_DEFAULT + '0', info->protocol != NET_PROTOCOL_VERSION ? '*' : ' ', info->numplayers, info->maxplayers, info->name);
1058 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);
1059 if( serverlist_cache[n].query == SQS_QUERIED ) {
1060 ServerList_ViewList_Remove( &serverlist_cache[n] );
1062 // if not in the slist menu we should print the server to console (if wanted)
1063 else if( serverlist_consoleoutput )
1064 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1065 // and finally, update the view set
1066 ServerList_ViewList_Insert( &serverlist_cache[n] );
1067 serverlist_cache[n].query = SQS_QUERIED;
1071 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1073 // Extract the IP addresses
1077 if (serverlist_consoleoutput)
1078 Con_Print("received server list...\n");
1079 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1083 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1084 if (developer.integer)
1085 Con_Printf("Requesting info from server %s\n", ipstring);
1086 // ignore the rest of the message if the serverlist is full
1087 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1089 // also ignore it if we have already queried it (other master server response)
1090 for( n = 0 ; n < serverlist_cachecount ; n++ )
1091 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1093 if( n >= serverlist_cachecount )
1097 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1098 // store the data the engine cares about (address and ping)
1099 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1100 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1101 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1103 ++serverlist_cachecount;
1106 // move on to next address in packet
1110 // begin or resume serverlist queries
1111 serverlist_querysleep = false;
1115 if (!strncmp(string, "ping", 4))
1117 if (developer.integer)
1118 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1119 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1122 if (!strncmp(string, "ack", 3))
1125 // we may not have liked the packet, but it was a command packet, so
1126 // we're done processing this packet now
1129 // netquake control packets, supported for compatibility only
1130 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1135 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1139 if (developer.integer)
1140 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1141 if (cls.connect_trying)
1143 lhnetaddress_t clientportaddress;
1144 clientportaddress = *peeraddress;
1147 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1150 LHNETADDRESS_SetPort(&clientportaddress, port);
1152 M_Update_Return_Reason("Accepted");
1153 NetConn_ConnectionEstablished(mysocket, &clientportaddress);
1157 if (developer.integer)
1158 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1159 cls.connect_trying = false;
1160 M_Update_Return_Reason((char *)data);
1163 case CCREP_SERVER_INFO:
1164 if (developer.integer)
1165 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1166 if (cls.state != ca_dedicated)
1168 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1169 // string we just ignore it and keep the real address
1171 // serverlist only uses text addresses
1172 cname = UDP_AddrToString(readaddr);
1173 // search the cache for this server
1174 for (n = 0; n < hostCacheCount; n++)
1175 if (!strcmp(cname, serverlist[n].cname))
1178 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1181 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1182 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1183 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1184 serverlist[n].users = MSG_ReadByte();
1185 serverlist[n].maxusers = MSG_ReadByte();
1187 if (c != NET_PROTOCOL_VERSION)
1189 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1190 strcpy(serverlist[n].name, "*");
1191 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1193 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1197 case CCREP_PLAYER_INFO:
1198 // we got a CCREP_PLAYER_INFO??
1199 //if (developer.integer)
1200 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1202 case CCREP_RULE_INFO:
1203 // we got a CCREP_RULE_INFO??
1204 //if (developer.integer)
1205 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1211 // we may not have liked the packet, but it was a valid control
1212 // packet, so we're done processing this packet now
1216 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)
1217 CL_ParseServerMessage();
1221 void NetConn_QueryQueueFrame(void)
1227 static double querycounter = 0;
1229 if (serverlist_querysleep)
1232 // each time querycounter reaches 1.0 issue a query
1233 querycounter += host_realframetime * net_slist_queriespersecond.value;
1234 maxqueries = (int)querycounter;
1235 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1236 querycounter -= maxqueries;
1238 if( maxqueries == 0 ) {
1242 // scan serverlist and issue queries as needed
1243 serverlist_querysleep = true;
1245 timeouttime = realtime - net_slist_timeout.value;
1246 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1248 serverlist_entry_t *entry = &serverlist_cache[ index ];
1249 if( entry->query != SQS_QUERYING )
1254 serverlist_querysleep = false;
1255 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1260 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1262 lhnetaddress_t address;
1265 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1266 for (socket = 0; socket < cl_numsockets ; socket++) {
1267 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1270 entry->querytime = realtime;
1271 entry->querycounter++;
1273 // if not in the slist menu we should print the server to console
1274 if (serverlist_consoleoutput)
1275 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1281 entry->query = SQS_TIMEDOUT;
1286 void NetConn_ClientFrame(void)
1289 lhnetaddress_t peeraddress;
1291 NetConn_UpdateServerStuff();
1292 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1294 if (cls.connect_remainingtries == 0)
1295 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1296 cls.connect_nextsendtime = realtime + 1;
1297 cls.connect_remainingtries--;
1298 if (cls.connect_remainingtries <= -10)
1300 cls.connect_trying = false;
1301 M_Update_Return_Reason("Connect: Failed");
1304 // try challenge first (newer server)
1305 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1306 // then try netquake as a fallback (old server, or netquake)
1307 SZ_Clear(&net_message);
1308 // save space for the header, filled in later
1309 MSG_WriteLong(&net_message, 0);
1310 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1311 MSG_WriteString(&net_message, "QUAKE");
1312 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1313 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1314 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1315 SZ_Clear(&net_message);
1317 for (i = 0;i < cl_numsockets;i++) {
1318 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0) {
1319 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1322 NetConn_QueryQueueFrame();
1323 if (cls.netcon && realtime > cls.netcon->timeout)
1325 Con_Print("Connection timed out\n");
1327 Host_ShutdownServer (false);
1329 for (conn = netconn_list;conn;conn = conn->next)
1330 NetConn_ReSendMessage(conn);
1333 #define MAX_CHALLENGES 128
1336 lhnetaddress_t address;
1340 challenge[MAX_CHALLENGES];
1342 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1346 for (i = 0;i < bufferlength - 1;i++)
1350 c = rand () % (127 - 33) + 33;
1351 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1357 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1359 unsigned int nb_clients = 0, i;
1362 // How many clients are there?
1363 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1364 if (svs.clients[i].active)
1367 // TODO: we should add more information for the full status string
1368 length = dpsnprintf(out_msg, out_size,
1369 "\377\377\377\377%s\x0A"
1370 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1371 "\\clients\\%d\\mapname\\%s\\hostname\\%s""\\protocol\\%d"
1374 fullstatus ? "statusResponse" : "infoResponse",
1375 gamename, com_modname, svs.maxclients,
1376 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1377 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1378 fullstatus ? "\n" : "");
1380 // Make sure it fits in the buffer
1389 ptr = out_msg + length;
1390 left = (int)out_size - length;
1392 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1394 client_t *cl = &svs.clients[i];
1397 int nameind, cleanind;
1399 char cleanname [sizeof(cl->name)];
1401 // Remove all characters '"' and '\' in the player name
1406 curchar = cl->name[nameind++];
1407 if (curchar != '"' && curchar != '\\')
1409 cleanname[cleanind++] = curchar;
1410 if (cleanind == sizeof(cleanname) - 1)
1413 } while (curchar != '\0');
1415 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1417 (int)(cl->ping * 1000.0f),
1430 extern void SV_SendServerinfo (client_t *client);
1431 int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1433 int i, ret, clientnum, best;
1437 char *s, *string, response[512], addressstring2[128], stringbuf[16384];
1441 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1443 // received a command string - strip off the packaging and put it
1444 // into our string buffer with NULL termination
1447 length = min(length, (int)sizeof(stringbuf) - 1);
1448 memcpy(stringbuf, data, length);
1449 stringbuf[length] = 0;
1452 if (developer.integer)
1454 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1455 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1456 Com_HexDumpToConsole(data, length);
1459 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1461 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1463 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1465 if (besttime > challenge[i].time)
1466 besttime = challenge[best = i].time;
1468 // if we did not find an exact match, choose the oldest and
1469 // update address and string
1470 if (i == MAX_CHALLENGES)
1473 challenge[i].address = *peeraddress;
1474 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1476 challenge[i].time = realtime;
1477 // send the challenge
1478 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1481 if (length > 8 && !memcmp(string, "connect\\", 8))
1485 if ((s = SearchInfostring(string, "challenge")))
1487 // validate the challenge
1488 for (i = 0;i < MAX_CHALLENGES;i++)
1489 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1491 if (i < MAX_CHALLENGES)
1493 // check engine protocol
1494 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1496 if (developer.integer)
1497 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1498 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1502 // see if this is a duplicate connection request
1503 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1504 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1506 if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1508 // client is still trying to connect,
1509 // so we send a duplicate reply
1510 if (developer.integer)
1511 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1512 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1515 else if (clientnum < svs.maxclients)
1517 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1519 // client crashed and is coming back, keep their stuff intact
1520 SV_SendServerinfo(client);
1521 //host_client = client;
1522 //SV_DropClient (true);
1529 // this is a new client, find a slot
1530 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1531 if (!client->active)
1533 if (clientnum < svs.maxclients)
1535 // prepare the client struct
1536 if ((conn = NetConn_Open(mysocket, peeraddress)))
1538 // allocated connection
1539 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1540 if (developer.integer)
1541 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1542 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1543 // now set up the client
1544 SV_ConnectClient(clientnum, conn);
1545 NetConn_Heartbeat(1);
1551 if (developer.integer)
1552 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1553 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1561 if (length >= 7 && !memcmp(string, "getinfo", 7))
1563 const char *challenge = NULL;
1565 // If there was a challenge in the getinfo message
1566 if (length > 8 && string[7] == ' ')
1567 challenge = string + 8;
1569 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1571 if (developer.integer)
1572 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1573 NetConn_WriteString(mysocket, response, peeraddress);
1577 if (length >= 9 && !memcmp(string, "getstatus", 9))
1579 const char *challenge = NULL;
1581 // If there was a challenge in the getinfo message
1582 if (length > 10 && string[9] == ' ')
1583 challenge = string + 10;
1585 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1587 if (developer.integer)
1588 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1589 NetConn_WriteString(mysocket, response, peeraddress);
1594 if (!strncmp(string, "ping", 4))
1596 if (developer.integer)
1597 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1598 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1601 if (!strncmp(string, "ack", 3))
1604 // we may not have liked the packet, but it was a command packet, so
1605 // we're done processing this packet now
1608 // LordHavoc: disabled netquake control packet support in server
1612 // netquake control packets, supported for compatibility only
1613 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1618 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1622 //if (developer.integer)
1623 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1624 if (length >= (int)strlen("QUAKE") + 1 + 1)
1626 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1628 if (developer.integer)
1629 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1630 SZ_Clear(&net_message);
1631 // save space for the header, filled in later
1632 MSG_WriteLong(&net_message, 0);
1633 MSG_WriteByte(&net_message, CCREP_REJECT);
1634 MSG_WriteString(&net_message, "Incompatible version.\n");
1635 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1636 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1637 SZ_Clear(&net_message);
1641 // see if this is a duplicate connection request
1642 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1643 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1645 if (clientnum < svs.maxclients)
1647 // duplicate connection request
1648 if (realtime - client->connecttime < 2.0)
1650 // client is still trying to connect,
1651 // so we send a duplicate reply
1652 if (developer.integer)
1653 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1654 SZ_Clear(&net_message);
1655 // save space for the header, filled in later
1656 MSG_WriteLong(&net_message, 0);
1657 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1658 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1659 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1660 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1661 SZ_Clear(&net_message);
1664 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1666 SV_SendServerinfo(client);
1667 // the old client hasn't sent us anything
1668 // in quite a while, so kick off and let
1669 // the retry take care of it...
1670 //host_client = client;
1671 //SV_DropClient (true);
1677 // this is a new client, find a slot
1678 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1679 if (!client->active)
1681 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1683 // connect to the client
1684 // everything is allocated, just fill in the details
1685 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1686 if (developer.integer)
1687 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1688 // send back the info about the server connection
1689 SZ_Clear(&net_message);
1690 // save space for the header, filled in later
1691 MSG_WriteLong(&net_message, 0);
1692 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1693 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1694 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1695 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1696 SZ_Clear(&net_message);
1697 // now set up the client struct
1698 SV_ConnectClient(clientnum, conn);
1699 NetConn_Heartbeat(1);
1703 //if (developer.integer)
1704 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1705 // no room; try to let player know
1706 SZ_Clear(&net_message);
1707 // save space for the header, filled in later
1708 MSG_WriteLong(&net_message, 0);
1709 MSG_WriteByte(&net_message, CCREP_REJECT);
1710 MSG_WriteString(&net_message, "Server is full.\n");
1711 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1712 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1713 SZ_Clear(&net_message);
1720 case CCREQ_SERVER_INFO:
1721 if (developer.integer)
1722 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1723 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1725 if (developer.integer)
1726 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1727 SZ_Clear(&net_message);
1728 // save space for the header, filled in later
1729 MSG_WriteLong(&net_message, 0);
1730 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1731 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1732 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1733 MSG_WriteString(&net_message, hostname.string);
1734 MSG_WriteString(&net_message, sv.name);
1735 MSG_WriteByte(&net_message, net_activeconnections);
1736 MSG_WriteByte(&net_message, svs.maxclients);
1737 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1738 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1739 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1740 SZ_Clear(&net_message);
1743 case CCREQ_PLAYER_INFO:
1744 if (developer.integer)
1745 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1748 int playerNumber, activeNumber, clientNumber;
1751 playerNumber = MSG_ReadByte();
1753 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1754 if (client->active && ++activeNumber == playerNumber)
1756 if (clientNumber != svs.maxclients)
1758 SZ_Clear(&net_message);
1759 // save space for the header, filled in later
1760 MSG_WriteLong(&net_message, 0);
1761 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1762 MSG_WriteByte(&net_message, playerNumber);
1763 MSG_WriteString(&net_message, client->name);
1764 MSG_WriteLong(&net_message, client->colors);
1765 MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1766 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1767 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1768 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1769 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1770 SZ_Clear(&net_message);
1774 case CCREQ_RULE_INFO:
1775 if (developer.integer)
1776 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1782 // find the search start location
1783 prevCvarName = MSG_ReadString();
1784 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1786 // send the response
1787 SZ_Clear(&net_message);
1788 // save space for the header, filled in later
1789 MSG_WriteLong(&net_message, 0);
1790 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1793 MSG_WriteString(&net_message, var->name);
1794 MSG_WriteString(&net_message, var->string);
1796 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1797 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1798 SZ_Clear(&net_message);
1805 // we may not have liked the packet, but it was a valid control
1806 // packet, so we're done processing this packet now
1811 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1813 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1815 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length)) == 2)
1816 SV_ReadClientMessage();
1824 void NetConn_ServerFrame(void)
1827 lhnetaddress_t peeraddress;
1829 NetConn_UpdateServerStuff();
1830 for (i = 0;i < sv_numsockets;i++)
1831 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1832 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
1833 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1835 // never timeout loopback connections
1836 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1838 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
1839 SV_DropClient(false);
1842 for (conn = netconn_list;conn;conn = conn->next)
1843 NetConn_ReSendMessage(conn);
1846 void NetConn_QueryMasters(void)
1850 lhnetaddress_t masteraddress;
1851 lhnetaddress_t broadcastaddress;
1854 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
1857 // 26000 is the default quake server port, servers on other ports will not
1859 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
1860 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
1862 for (i = 0;i < cl_numsockets;i++)
1866 // search LAN for Quake servers
1867 SZ_Clear(&net_message);
1868 // save space for the header, filled in later
1869 MSG_WriteLong(&net_message, 0);
1870 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
1871 MSG_WriteString(&net_message, "QUAKE");
1872 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1873 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1874 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
1875 SZ_Clear(&net_message);
1877 // search LAN for DarkPlaces servers
1878 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
1880 // build the getservers message to send to the master servers
1881 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
1884 for (masternum = 0;sv_masters[masternum].name;masternum++)
1886 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
1889 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
1894 if (!masterquerycount)
1896 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
1897 M_Update_Return_Reason("No network");
1901 void NetConn_Heartbeat(int priority)
1903 lhnetaddress_t masteraddress;
1905 lhnetsocket_t *mysocket;
1907 // if it's a state change (client connected), limit next heartbeat to no
1908 // more than 30 sec in the future
1909 if (priority == 1 && nextheartbeattime > realtime + 30.0)
1910 nextheartbeattime = realtime + 30.0;
1912 // limit heartbeatperiod to 30 to 270 second range,
1913 // lower limit is to avoid abusing master servers with excess traffic,
1914 // upper limit is to avoid timing out on the master server (which uses
1916 if (sv_heartbeatperiod.value < 30)
1917 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
1918 if (sv_heartbeatperiod.value > 270)
1919 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
1921 // make advertising optional and don't advertise singleplayer games, and
1922 // only send a heartbeat as often as the admin wants
1923 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
1925 nextheartbeattime = realtime + sv_heartbeatperiod.value;
1926 for (masternum = 0;sv_masters[masternum].name;masternum++)
1927 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
1928 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
1932 int NetConn_SendToAll(sizebuf_t *data, double blocktime)
1935 unsigned char sent[MAX_SCOREBOARD];
1937 memset(sent, 0, sizeof(sent));
1939 // simultaneously wait for the first CanSendMessage and send the message,
1940 // then wait for a second CanSendMessage (verifying it was received), or
1941 // the client drops and is no longer counted
1942 // the loop aborts when either it runs out of clients to send to, or a
1944 blocktime += Sys_DoubleTime();
1948 // run a network frame to check for packets
1949 NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
1950 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1952 if (host_client->netconnection)
1954 if (NetConn_CanSendMessage(host_client->netconnection))
1957 NetConn_SendReliableMessage(host_client->netconnection, data);
1960 if (!NetConn_CanSendMessage(host_client->netconnection))
1965 while (count && Sys_DoubleTime() < blocktime);
1969 static void Net_Heartbeat_f(void)
1972 NetConn_Heartbeat(2);
1974 Con_Print("No server running, can not heartbeat to master server.\n");
1977 void PrintStats(netconn_t *conn)
1979 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, conn->canSend, conn->sendSequence, conn->receiveSequence);
1982 void Net_Stats_f(void)
1985 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
1986 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
1987 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
1988 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
1989 Con_Printf("packetsSent = %i\n", packetsSent);
1990 Con_Printf("packetsReSent = %i\n", packetsReSent);
1991 Con_Printf("packetsReceived = %i\n", packetsReceived);
1992 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
1993 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
1994 Con_Print("connections =\n");
1995 for (conn = netconn_list;conn;conn = conn->next)
1999 void Net_Slist_f(void)
2001 ServerList_ResetMasks();
2002 serverlist_sortbyfield = SLIF_PING;
2003 serverlist_sortdescending = false;
2004 if (m_state != m_slist) {
2005 Con_Print("Sending requests to master servers\n");
2006 ServerList_QueryList();
2007 serverlist_consoleoutput = true;
2008 Con_Print("Listening for replies...\n");
2010 ServerList_QueryList();
2013 void NetConn_Init(void)
2016 lhnetaddress_t tempaddress;
2017 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2018 Cmd_AddCommand("net_stats", Net_Stats_f);
2019 Cmd_AddCommand("net_slist", Net_Slist_f);
2020 Cmd_AddCommand("heartbeat", Net_Heartbeat_f);
2021 Cvar_RegisterVariable(&net_slist_queriespersecond);
2022 Cvar_RegisterVariable(&net_slist_queriesperframe);
2023 Cvar_RegisterVariable(&net_slist_timeout);
2024 Cvar_RegisterVariable(&net_slist_maxtries);
2025 Cvar_RegisterVariable(&net_messagetimeout);
2026 Cvar_RegisterVariable(&net_messagerejointimeout);
2027 Cvar_RegisterVariable(&net_connecttimeout);
2028 Cvar_RegisterVariable(&cl_netlocalping);
2029 Cvar_RegisterVariable(&cl_netpacketloss);
2030 Cvar_RegisterVariable(&hostname);
2031 Cvar_RegisterVariable(&developer_networking);
2032 Cvar_RegisterVariable(&cl_netport);
2033 Cvar_RegisterVariable(&sv_netport);
2034 Cvar_RegisterVariable(&net_address);
2035 //Cvar_RegisterVariable(&net_address_ipv6);
2036 Cvar_RegisterVariable(&sv_public);
2037 Cvar_RegisterVariable(&sv_heartbeatperiod);
2038 for (i = 0;sv_masters[i].name;i++)
2039 Cvar_RegisterVariable(&sv_masters[i]);
2040 // 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.
2041 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2043 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2045 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2046 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2049 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2051 // 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
2052 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2054 i = atoi(com_argv[i + 1]);
2055 if (i >= 0 && i < 65536)
2057 Con_Printf("-port option used, setting port cvar to %i\n", i);
2058 Cvar_SetValueQuick(&sv_netport, i);
2061 Con_Printf("-port option used, but %i is not a valid port number\n", i);
2065 net_message.data = net_message_buf;
2066 net_message.maxsize = sizeof(net_message_buf);
2067 net_message.cursize = 0;
2071 void NetConn_Shutdown(void)
2073 NetConn_CloseClientPorts();
2074 NetConn_CloseServerPorts();