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", "advertises this server on the master server (so that players can find it in the server browser)"};
30 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
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", "", "user-chosen master server 1"},
36 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
37 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
38 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
39 {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40 {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
41 {0, "sv_masterextra3", "12.166.196.192", "default master server 3 (admin: Venim)"}, // admin: Venim
42 {0, "sv_masterextra4", "excalibur.nvg.ntnu.no", "default master server 4 (admin: tChr)"}, // 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", "drops players who have not sent any packets for this many seconds"};
52 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10", "give a player this much time in seconds to rejoin and continue playing (not losing frags and such)"};
53 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
54 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
55 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
57 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
58 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0", "drops this percentage of packets (incoming and outgoing), useful for testing network protocol robustness (effects failing to start, sounds failing to play, etc)"};
59 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
60 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
61 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
62 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
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", "forces client to use chosen port number if not 0"};
97 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
98 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
99 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
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_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol)
437 if (protocol == PROTOCOL_QUAKEWORLD)
440 qboolean sendreliable;
442 if (data->cursize == 0 && conn->message.cursize == 0)
444 Con_Printf ("Datagram_SendUnreliableMessage: zero length message\n");
448 sendreliable = false;
449 // if the remote side dropped the last reliable message, resend it
450 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
452 // if the reliable transmit buffer is empty, copy the current message out
453 if (!conn->sendMessageLength && conn->message.cursize)
455 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
456 conn->sendMessageLength = conn->message.cursize;
457 SZ_Clear(&conn->message); // clear the message buffer
458 conn->qw.reliable_sequence ^= 1;
461 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
462 *((int *)(sendbuffer + 0)) = LittleLong(conn->qw.outgoing_sequence | (sendreliable<<31));
463 // last received unreliable packet number, and last received reliable packet number (0 or 1)
464 *((int *)(sendbuffer + 4)) = LittleLong(conn->qw.incoming_sequence | (conn->qw.incoming_reliable_sequence<<31));
466 // client sends qport in every packet
467 if (conn == cls.netcon)
469 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
472 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) + data->cursize > (int)sizeof(sendbuffer))
474 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
479 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
480 packetLen += conn->sendMessageLength;
482 memcpy(sendbuffer + packetLen, data->data, data->cursize);
483 packetLen += data->cursize;
484 conn->qw.outgoing_sequence++;
486 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
489 unreliableMessagesSent++;
494 unsigned int packetLen;
495 unsigned int dataLen;
497 unsigned int *header;
499 // if a reliable message fragment has been lost, send it again
500 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
502 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
504 dataLen = conn->sendMessageLength;
509 dataLen = MAX_PACKETFRAGMENT;
513 packetLen = NET_HEADERSIZE + dataLen;
515 header = (unsigned int *)sendbuffer;
516 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
517 header[1] = BigLong(conn->nq.sendSequence - 1);
518 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
520 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
522 conn->lastSendTime = realtime;
527 // if we have a new reliable message to send, do so
528 if (!conn->sendMessageLength && conn->message.cursize)
530 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
532 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, sizeof(conn->sendMessage));
533 conn->message.overflowed = true;
537 if (developer_networking.integer && conn == cls.netcon)
539 Con_Print("client sending reliable message to server:\n");
540 SZ_HexDumpToConsole(&conn->message);
543 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
544 conn->sendMessageLength = conn->message.cursize;
545 SZ_Clear(&conn->message);
547 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
549 dataLen = conn->sendMessageLength;
554 dataLen = MAX_PACKETFRAGMENT;
558 packetLen = NET_HEADERSIZE + dataLen;
560 header = (unsigned int *)sendbuffer;
561 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
562 header[1] = BigLong(conn->nq.sendSequence);
563 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
565 conn->nq.sendSequence++;
567 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
569 conn->lastSendTime = realtime;
571 reliableMessagesSent++;
574 // if we have an unreliable message to send, do so
577 packetLen = NET_HEADERSIZE + data->cursize;
579 if (packetLen > (int)sizeof(sendbuffer))
581 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
585 header = (unsigned int *)sendbuffer;
586 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
587 header[1] = BigLong(conn->nq.unreliableSendSequence);
588 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
590 conn->nq.unreliableSendSequence++;
592 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
595 unreliableMessagesSent++;
601 void NetConn_CloseClientPorts(void)
603 for (;cl_numsockets > 0;cl_numsockets--)
604 if (cl_sockets[cl_numsockets - 1])
605 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
608 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
610 lhnetaddress_t address;
612 char addressstring2[1024];
613 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
615 if ((s = LHNET_OpenSocket_Connectionless(&address)))
617 cl_sockets[cl_numsockets++] = s;
618 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
619 Con_Printf("Client opened a socket on address %s\n", addressstring2);
623 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
624 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
628 Con_Printf("Client unable to parse address %s\n", addressstring);
631 void NetConn_OpenClientPorts(void)
634 NetConn_CloseClientPorts();
635 port = bound(0, cl_netport.integer, 65535);
636 if (cl_netport.integer != port)
637 Cvar_SetValueQuick(&cl_netport, port);
638 Con_Printf("Client using port %i\n", port);
639 NetConn_OpenClientPort("local:2", 0);
640 NetConn_OpenClientPort(net_address.string, port);
641 //NetConn_OpenClientPort(net_address_ipv6.string, port);
644 void NetConn_CloseServerPorts(void)
646 for (;sv_numsockets > 0;sv_numsockets--)
647 if (sv_sockets[sv_numsockets - 1])
648 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
651 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
653 lhnetaddress_t address;
656 char addressstring2[1024];
658 for (port = defaultport; port <= defaultport + 100; port++)
660 if (LHNETADDRESS_FromString(&address, addressstring, port))
662 if ((s = LHNET_OpenSocket_Connectionless(&address)))
664 sv_sockets[sv_numsockets++] = s;
665 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
666 Con_Printf("Server listening on address %s\n", addressstring2);
671 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
672 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
677 Con_Printf("Server unable to parse address %s\n", addressstring);
678 // if it cant parse one address, it wont be able to parse another for sure
684 void NetConn_OpenServerPorts(int opennetports)
687 NetConn_CloseServerPorts();
688 NetConn_UpdateSockets();
689 port = bound(0, sv_netport.integer, 65535);
692 Con_Printf("Server using port %i\n", port);
693 if (sv_netport.integer != port)
694 Cvar_SetValueQuick(&sv_netport, port);
695 if (cls.state != ca_dedicated)
696 NetConn_OpenServerPort("local:1", 0);
699 NetConn_OpenServerPort(net_address.string, port);
700 //NetConn_OpenServerPort(net_address_ipv6.string, port);
702 if (sv_numsockets == 0)
703 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
706 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
708 int i, a = LHNETADDRESS_GetAddressType(address);
709 for (i = 0;i < cl_numsockets;i++)
710 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
711 return cl_sockets[i];
715 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
717 int i, a = LHNETADDRESS_GetAddressType(address);
718 for (i = 0;i < sv_numsockets;i++)
719 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
720 return sv_sockets[i];
724 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
727 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
728 conn->mysocket = mysocket;
729 conn->peeraddress = *peeraddress;
730 conn->lastMessageTime = realtime;
731 conn->message.data = conn->messagedata;
732 conn->message.maxsize = sizeof(conn->messagedata);
733 conn->message.cursize = 0;
734 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
735 // reduce effectiveness of connection request floods
736 conn->timeout = realtime + net_connecttimeout.value;
737 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
738 conn->next = netconn_list;
743 void NetConn_Close(netconn_t *conn)
746 // remove connection from list
747 if (conn == netconn_list)
748 netconn_list = conn->next;
751 for (c = netconn_list;c;c = c->next)
755 c->next = conn->next;
759 // not found in list, we'll avoid crashing here...
767 static int clientport = -1;
768 static int clientport2 = -1;
769 static int hostport = -1;
770 void NetConn_UpdateSockets(void)
772 if (cls.state != ca_dedicated)
774 if (clientport2 != cl_netport.integer)
776 clientport2 = cl_netport.integer;
777 if (cls.state == ca_connected)
778 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
780 if (cls.state == ca_disconnected && clientport != clientport2)
782 clientport = clientport2;
783 NetConn_CloseClientPorts();
785 if (cl_numsockets == 0)
786 NetConn_OpenClientPorts();
789 if (hostport != sv_netport.integer)
791 hostport = sv_netport.integer;
793 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
797 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol)
802 if (protocol == PROTOCOL_QUAKEWORLD)
804 int sequence, sequence_ack;
805 int reliable_ack, reliable_message;
809 sequence = LittleLong(*((int *)(data + 0)));
810 sequence_ack = LittleLong(*((int *)(data + 4)));
814 if (conn != cls.netcon)
819 // TODO: use qport to identify that this client really is who they say they are? (and elsewhere in the code to identify the connection without a port match?)
820 qport = LittleShort(*((int *)(data + 8)));
826 reliable_message = sequence >> 31;
827 reliable_ack = sequence_ack >> 31;
828 sequence &= ~(1<<31);
829 sequence_ack &= ~(1<<31);
830 if (sequence <= conn->qw.incoming_sequence)
832 Con_DPrint("Got a stale datagram\n");
835 count = sequence - (conn->qw.incoming_sequence + 1);
838 droppedDatagrams += count;
839 Con_DPrintf("Dropped %u datagram(s)\n", count);
841 if (reliable_ack == conn->qw.reliable_sequence)
843 // received, now we will be able to send another reliable message
844 conn->sendMessageLength = 0;
845 reliableMessagesReceived++;
847 conn->qw.incoming_sequence = sequence;
848 conn->qw.incoming_acknowledged = sequence_ack;
849 conn->qw.incoming_reliable_acknowledged = reliable_ack;
850 if (reliable_message)
851 conn->qw.incoming_reliable_sequence ^= 1;
852 conn->lastMessageTime = realtime;
853 conn->timeout = realtime + net_messagetimeout.value;
854 unreliableMessagesReceived++;
855 SZ_Clear(&net_message);
856 SZ_Write(&net_message, data, length);
864 unsigned int sequence;
867 qlength = (unsigned int)BigLong(((int *)data)[0]);
868 flags = qlength & ~NETFLAG_LENGTH_MASK;
869 qlength &= NETFLAG_LENGTH_MASK;
870 // control packets were already handled
871 if (!(flags & NETFLAG_CTL) && qlength == length)
873 sequence = BigLong(((int *)data)[1]);
877 if (flags & NETFLAG_UNRELIABLE)
879 if (sequence >= conn->nq.unreliableReceiveSequence)
881 if (sequence > conn->nq.unreliableReceiveSequence)
883 count = sequence - conn->nq.unreliableReceiveSequence;
884 droppedDatagrams += count;
885 Con_DPrintf("Dropped %u datagram(s)\n", count);
887 conn->nq.unreliableReceiveSequence = sequence + 1;
888 conn->lastMessageTime = realtime;
889 conn->timeout = realtime + net_messagetimeout.value;
890 unreliableMessagesReceived++;
893 SZ_Clear(&net_message);
894 SZ_Write(&net_message, data, length);
900 Con_DPrint("Got a stale datagram\n");
903 else if (flags & NETFLAG_ACK)
905 if (sequence == (conn->nq.sendSequence - 1))
907 if (sequence == conn->nq.ackSequence)
909 conn->nq.ackSequence++;
910 if (conn->nq.ackSequence != conn->nq.sendSequence)
911 Con_DPrint("ack sequencing error\n");
912 conn->lastMessageTime = realtime;
913 conn->timeout = realtime + net_messagetimeout.value;
914 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
916 unsigned int packetLen;
917 unsigned int dataLen;
919 unsigned int *header;
921 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
922 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
924 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
926 dataLen = conn->sendMessageLength;
931 dataLen = MAX_PACKETFRAGMENT;
935 packetLen = NET_HEADERSIZE + dataLen;
937 header = (unsigned int *)sendbuffer;
938 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
939 header[1] = BigLong(conn->nq.sendSequence);
940 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
942 conn->nq.sendSequence++;
944 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
946 conn->lastSendTime = realtime;
951 conn->sendMessageLength = 0;
954 Con_DPrint("Duplicate ACK received\n");
957 Con_DPrint("Stale ACK received\n");
960 else if (flags & NETFLAG_DATA)
962 unsigned int temppacket[2];
963 temppacket[0] = BigLong(8 | NETFLAG_ACK);
964 temppacket[1] = BigLong(sequence);
965 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
966 if (sequence == conn->nq.receiveSequence)
968 conn->lastMessageTime = realtime;
969 conn->timeout = realtime + net_messagetimeout.value;
970 conn->nq.receiveSequence++;
971 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
972 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
973 conn->receiveMessageLength += length;
975 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
976 "Dropping the message!\n", sequence );
977 conn->receiveMessageLength = 0;
980 if (flags & NETFLAG_EOM)
982 reliableMessagesReceived++;
983 length = conn->receiveMessageLength;
984 conn->receiveMessageLength = 0;
987 SZ_Clear(&net_message);
988 SZ_Write(&net_message, conn->receiveMessage, length);
995 receivedDuplicateCount++;
1003 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1005 cls.connect_trying = false;
1006 M_Update_Return_Reason("");
1007 // the connection request succeeded, stop current connection and set up a new connection
1009 // if we're connecting to a remote server, shut down any local server
1010 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1011 Host_ShutdownServer ();
1012 // allocate a net connection to keep track of things
1013 cls.netcon = NetConn_Open(mysocket, peeraddress);
1014 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1015 key_dest = key_game;
1017 cls.demonum = -1; // not in the demo loop now
1018 cls.state = ca_connected;
1019 cls.signon = 0; // need all the signon messages before playing
1020 cls.protocol = initialprotocol;
1021 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1022 Cmd_ForwardStringToServer("new");
1025 int NetConn_IsLocalGame(void)
1027 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1032 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1034 qboolean fromserver;
1035 int ret, c, control;
1037 char *string, addressstring2[128], cname[128], ipstring[32];
1038 char stringbuf[16384];
1040 // quakeworld ingame packet
1041 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1043 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1045 // received a command string - strip off the packaging and put it
1046 // into our string buffer with NULL termination
1049 length = min(length, (int)sizeof(stringbuf) - 1);
1050 memcpy(stringbuf, data, length);
1051 stringbuf[length] = 0;
1054 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1056 if (developer.integer)
1058 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1059 Com_HexDumpToConsole(data, length);
1062 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1064 // darkplaces or quake3
1065 char protocolnames[1400];
1066 Protocol_Names(protocolnames, sizeof(protocolnames));
1067 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1068 M_Update_Return_Reason("Got challenge response");
1069 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1072 if (length > 1 && string[0] == 'c' && string[1] >= '0' && string[1] <= '9')
1075 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1076 Con_Printf("\"%s\" received, sending QuakeWorld connect request back to %s\n", string, addressstring2);
1077 M_Update_Return_Reason("Got QuakeWorld challenge response");
1078 cls.qw_qport = qport.integer;
1079 NetConn_WriteString(mysocket, va("\377\377\377\377connect 28 %i %i \"%s\"\n", cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1081 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1083 // darkplaces or quake3
1084 M_Update_Return_Reason("Accepted");
1085 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1088 if (length > 1 && string[0] == 'j' && cls.connect_trying)
1091 M_Update_Return_Reason("QuakeWorld Accepted");
1092 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1095 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1097 char rejectreason[32];
1098 cls.connect_trying = false;
1100 length = max(length - 7, (int)sizeof(rejectreason) - 1);
1101 memcpy(rejectreason, string, length);
1102 rejectreason[length] = 0;
1103 M_Update_Return_Reason(rejectreason);
1106 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1108 serverlist_info_t *info;
1113 // serverlist only uses text addresses
1114 LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true);
1115 // search the cache for this server and update it
1116 for( n = 0; n < serverlist_cachecount; n++ )
1117 if( !strcmp( cname, serverlist_cache[n].info.cname ) )
1119 if( n == serverlist_cachecount ) {
1120 // LAN search doesnt require an answer from the master server so we wont
1121 // know the ping nor will it be initialized already...
1124 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1127 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1128 // store the data the engine cares about (address and ping)
1129 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1130 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1131 serverlist_cache[serverlist_cachecount].querytime = realtime;
1132 // if not in the slist menu we should print the server to console
1133 if (serverlist_consoleoutput) {
1134 Con_Printf("querying %s\n", ipstring);
1137 ++serverlist_cachecount;
1140 info = &serverlist_cache[n].info;
1141 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1142 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1143 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1144 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1145 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1146 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1147 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1149 if (info->ping == 100000)
1152 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0);
1153 pingtime = bound(0, pingtime, 9999);
1155 info->ping = pingtime;
1157 // legacy/old stuff move it to the menu ASAP
1159 // build description strings for the things users care about
1160 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);
1161 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);
1162 if( serverlist_cache[n].query == SQS_QUERIED ) {
1163 ServerList_ViewList_Remove( &serverlist_cache[n] );
1165 // if not in the slist menu we should print the server to console (if wanted)
1166 else if( serverlist_consoleoutput )
1167 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1168 // and finally, update the view set
1169 ServerList_ViewList_Insert( &serverlist_cache[n] );
1170 serverlist_cache[n].query = SQS_QUERIED;
1174 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1176 // Extract the IP addresses
1180 if (serverlist_consoleoutput)
1181 Con_Print("received server list...\n");
1182 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1186 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]);
1187 if (developer.integer)
1188 Con_Printf("Requesting info from server %s\n", ipstring);
1189 // ignore the rest of the message if the serverlist is full
1190 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1192 // also ignore it if we have already queried it (other master server response)
1193 for( n = 0 ; n < serverlist_cachecount ; n++ )
1194 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1196 if( n >= serverlist_cachecount )
1200 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1201 // store the data the engine cares about (address and ping)
1202 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1203 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1204 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1206 ++serverlist_cachecount;
1209 // move on to next address in packet
1213 // begin or resume serverlist queries
1214 serverlist_querysleep = false;
1218 if (!strncmp(string, "ping", 4))
1220 if (developer.integer)
1221 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1222 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1225 if (!strncmp(string, "ack", 3))
1228 // QuakeWorld compatibility
1229 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1232 M_Update_Return_Reason("Accepted");
1233 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1236 if (length > 1 && string[0] == 'c' && string[1] >= '0' && string[1] <= '9' && cls.connect_trying)
1238 // challenge message
1239 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1240 Con_Printf("challenge %s received, sending connect request back to %s\n", string + 1, addressstring2);
1241 M_Update_Return_Reason("Got challenge response");
1242 cls.qw_qport = qport.integer;
1243 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1244 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "name", cl_name.string);
1245 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "topcolor", va("%i", (cl_color.integer >> 4) & 15));
1246 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "bottomcolor", va("%i", (cl_color.integer) & 15));
1247 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "rate", va("%i", cl_rate.integer));
1248 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "msg", "1");
1249 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ver", engineversion);
1250 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1253 if (string[0] == 'n')
1256 Con_Printf("QW print command from server at %s:\n", addressstring2, string + 1);
1258 // we may not have liked the packet, but it was a command packet, so
1259 // we're done processing this packet now
1262 // quakeworld ingame packet
1263 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2)
1266 CL_ParseServerMessage();
1269 // netquake control packets, supported for compatibility only
1270 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1275 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1279 if (developer.integer)
1280 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1281 if (cls.connect_trying)
1283 lhnetaddress_t clientportaddress;
1284 clientportaddress = *peeraddress;
1287 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1290 LHNETADDRESS_SetPort(&clientportaddress, port);
1292 M_Update_Return_Reason("Accepted");
1293 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1297 if (developer.integer)
1298 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1299 cls.connect_trying = false;
1300 M_Update_Return_Reason((char *)data);
1303 case CCREP_SERVER_INFO:
1304 if (developer.integer)
1305 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1306 if (cls.state != ca_dedicated)
1308 // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address
1309 // string we just ignore it and keep the real address
1311 // serverlist only uses text addresses
1312 cname = UDP_AddrToString(readaddr);
1313 // search the cache for this server
1314 for (n = 0; n < hostCacheCount; n++)
1315 if (!strcmp(cname, serverlist[n].cname))
1318 if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE)
1321 memset(&serverlist[n], 0, sizeof(serverlist[n]));
1322 strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name));
1323 strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map));
1324 serverlist[n].users = MSG_ReadByte();
1325 serverlist[n].maxusers = MSG_ReadByte();
1327 if (c != NET_PROTOCOL_VERSION)
1329 strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname));
1330 strcpy(serverlist[n].name, "*");
1331 strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name));
1333 strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname));
1337 case CCREP_PLAYER_INFO:
1338 // we got a CCREP_PLAYER_INFO??
1339 //if (developer.integer)
1340 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1342 case CCREP_RULE_INFO:
1343 // we got a CCREP_RULE_INFO??
1344 //if (developer.integer)
1345 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1351 // we may not have liked the packet, but it was a valid control
1352 // packet, so we're done processing this packet now
1356 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2)
1357 CL_ParseServerMessage();
1361 void NetConn_QueryQueueFrame(void)
1367 static double querycounter = 0;
1369 if (serverlist_querysleep)
1372 // each time querycounter reaches 1.0 issue a query
1373 querycounter += host_realframetime * net_slist_queriespersecond.value;
1374 maxqueries = (int)querycounter;
1375 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1376 querycounter -= maxqueries;
1378 if( maxqueries == 0 ) {
1382 // scan serverlist and issue queries as needed
1383 serverlist_querysleep = true;
1385 timeouttime = realtime - net_slist_timeout.value;
1386 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1388 serverlist_entry_t *entry = &serverlist_cache[ index ];
1389 if( entry->query != SQS_QUERYING )
1394 serverlist_querysleep = false;
1395 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1400 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1402 lhnetaddress_t address;
1405 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1406 for (socket = 0; socket < cl_numsockets ; socket++) {
1407 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1410 entry->querytime = realtime;
1411 entry->querycounter++;
1413 // if not in the slist menu we should print the server to console
1414 if (serverlist_consoleoutput)
1415 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1421 entry->query = SQS_TIMEDOUT;
1426 void NetConn_ClientFrame(void)
1429 lhnetaddress_t peeraddress;
1430 NetConn_UpdateSockets();
1431 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1433 if (cls.connect_remainingtries == 0)
1434 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1435 cls.connect_nextsendtime = realtime + 1;
1436 cls.connect_remainingtries--;
1437 if (cls.connect_remainingtries <= -10)
1439 cls.connect_trying = false;
1440 M_Update_Return_Reason("Connect: Failed");
1443 // try challenge first (newer DP server or QW)
1444 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1445 // then try netquake as a fallback (old server, or netquake)
1446 SZ_Clear(&net_message);
1447 // save space for the header, filled in later
1448 MSG_WriteLong(&net_message, 0);
1449 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1450 MSG_WriteString(&net_message, "QUAKE");
1451 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1452 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1453 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1454 SZ_Clear(&net_message);
1456 for (i = 0;i < cl_numsockets;i++)
1457 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1458 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1459 NetConn_QueryQueueFrame();
1460 if (cls.netcon && realtime > cls.netcon->timeout)
1462 Con_Print("Connection timed out\n");
1464 Host_ShutdownServer ();
1468 #define MAX_CHALLENGES 128
1471 lhnetaddress_t address;
1475 challenge[MAX_CHALLENGES];
1477 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1481 for (i = 0;i < bufferlength - 1;i++)
1485 c = rand () % (127 - 33) + 33;
1486 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1492 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1494 unsigned int nb_clients = 0, i;
1497 // How many clients are there?
1498 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1499 if (svs.clients[i].active)
1502 // TODO: we should add more information for the full status string
1503 length = dpsnprintf(out_msg, out_size,
1504 "\377\377\377\377%s\x0A"
1505 "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d"
1506 "\\clients\\%d\\mapname\\%s\\hostname\\%s""\\protocol\\%d"
1509 fullstatus ? "statusResponse" : "infoResponse",
1510 gamename, com_modname, svs.maxclients,
1511 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1512 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1513 fullstatus ? "\n" : "");
1515 // Make sure it fits in the buffer
1524 ptr = out_msg + length;
1525 left = (int)out_size - length;
1527 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1529 client_t *cl = &svs.clients[i];
1532 int nameind, cleanind;
1534 char cleanname [sizeof(cl->name)];
1536 // Remove all characters '"' and '\' in the player name
1541 curchar = cl->name[nameind++];
1542 if (curchar != '"' && curchar != '\\')
1544 cleanname[cleanind++] = curchar;
1545 if (cleanind == sizeof(cleanname) - 1)
1548 } while (curchar != '\0');
1550 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1552 (int)(cl->ping * 1000.0f),
1565 extern void SV_SendServerinfo (client_t *client);
1566 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1568 int i, ret, clientnum, best;
1572 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1574 // see if we can identify the sender as a local player
1575 // (this is necessary for rcon to send a reliable reply if the client is
1576 // actually on the server, not sending remotely)
1577 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1578 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1580 if (i == svs.maxclients)
1585 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1587 // received a command string - strip off the packaging and put it
1588 // into our string buffer with NULL termination
1591 length = min(length, (int)sizeof(stringbuf) - 1);
1592 memcpy(stringbuf, data, length);
1593 stringbuf[length] = 0;
1596 if (developer.integer)
1598 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1599 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1600 Com_HexDumpToConsole(data, length);
1603 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1605 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1607 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1609 if (besttime > challenge[i].time)
1610 besttime = challenge[best = i].time;
1612 // if we did not find an exact match, choose the oldest and
1613 // update address and string
1614 if (i == MAX_CHALLENGES)
1617 challenge[i].address = *peeraddress;
1618 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1620 challenge[i].time = realtime;
1621 // send the challenge
1622 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1625 if (length > 8 && !memcmp(string, "connect\\", 8))
1629 if ((s = SearchInfostring(string, "challenge")))
1631 // validate the challenge
1632 for (i = 0;i < MAX_CHALLENGES;i++)
1633 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1635 if (i < MAX_CHALLENGES)
1637 // check engine protocol
1638 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1640 if (developer.integer)
1641 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1642 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1646 // see if this is a duplicate connection request
1647 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1648 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1650 if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1652 // client is still trying to connect,
1653 // so we send a duplicate reply
1654 if (developer.integer)
1655 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1656 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1659 else if (clientnum < svs.maxclients)
1661 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1663 // client crashed and is coming back, keep their stuff intact
1664 SV_SendServerinfo(client);
1665 //host_client = client;
1666 //SV_DropClient (true);
1673 // this is a new client, find a slot
1674 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1675 if (!client->active)
1677 if (clientnum < svs.maxclients)
1679 // prepare the client struct
1680 if ((conn = NetConn_Open(mysocket, peeraddress)))
1682 // allocated connection
1683 LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true);
1684 if (developer.integer)
1685 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1686 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1687 // now set up the client
1689 SV_ConnectClient(clientnum, conn);
1691 NetConn_Heartbeat(1);
1697 if (developer.integer)
1698 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1699 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1707 if (length >= 7 && !memcmp(string, "getinfo", 7))
1709 const char *challenge = NULL;
1711 // If there was a challenge in the getinfo message
1712 if (length > 8 && string[7] == ' ')
1713 challenge = string + 8;
1715 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1717 if (developer.integer)
1718 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1719 NetConn_WriteString(mysocket, response, peeraddress);
1723 if (length >= 9 && !memcmp(string, "getstatus", 9))
1725 const char *challenge = NULL;
1727 // If there was a challenge in the getinfo message
1728 if (length > 10 && string[9] == ' ')
1729 challenge = string + 10;
1731 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1733 if (developer.integer)
1734 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1735 NetConn_WriteString(mysocket, response, peeraddress);
1739 if (length >= 5 && !memcmp(string, "rcon ", 5))
1742 char *s = string + 5;
1744 for (i = 0;*s > ' ';s++)
1745 if (i < (int)sizeof(password) - 1)
1748 if (password[0] > ' ' && !strcmp(rcon_password.string, password))
1750 // looks like a legitimate rcon command with the correct password
1751 Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s);
1752 rcon_redirect = true;
1753 rcon_redirect_bufferpos = 0;
1754 Cmd_ExecuteString(s, src_command);
1755 rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
1756 rcon_redirect = false;
1757 // print resulting text to client
1758 // if client is playing, send a reliable reply instead of
1762 // if the netconnection is loop, then this is the
1763 // local player on a listen mode server, and it would
1764 // result in duplicate printing to the console
1765 // (not that the local player should be using rcon
1766 // when they have the console)
1767 if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1768 SV_ClientPrintf("%s", rcon_redirect_buffer);
1773 dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
1774 NetConn_WriteString(mysocket, response, peeraddress);
1780 if (!strncmp(string, "ping", 4))
1782 if (developer.integer)
1783 Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr));
1784 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1787 if (!strncmp(string, "ack", 3))
1790 // we may not have liked the packet, but it was a command packet, so
1791 // we're done processing this packet now
1794 // LordHavoc: disabled netquake control packet support in server
1798 // netquake control packets, supported for compatibility only
1799 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1804 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1808 //if (developer.integer)
1809 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1810 if (length >= (int)strlen("QUAKE") + 1 + 1)
1812 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1814 if (developer.integer)
1815 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1816 SZ_Clear(&net_message);
1817 // save space for the header, filled in later
1818 MSG_WriteLong(&net_message, 0);
1819 MSG_WriteByte(&net_message, CCREP_REJECT);
1820 MSG_WriteString(&net_message, "Incompatible version.\n");
1821 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1822 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1823 SZ_Clear(&net_message);
1827 // see if this is a duplicate connection request
1828 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1829 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1831 if (clientnum < svs.maxclients)
1833 // duplicate connection request
1834 if (realtime - client->connecttime < 2.0)
1836 // client is still trying to connect,
1837 // so we send a duplicate reply
1838 if (developer.integer)
1839 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1840 SZ_Clear(&net_message);
1841 // save space for the header, filled in later
1842 MSG_WriteLong(&net_message, 0);
1843 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1844 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1845 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1846 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1847 SZ_Clear(&net_message);
1850 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1852 SV_SendServerinfo(client);
1853 // the old client hasn't sent us anything
1854 // in quite a while, so kick off and let
1855 // the retry take care of it...
1856 //host_client = client;
1857 //SV_DropClient (true);
1863 // this is a new client, find a slot
1864 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1865 if (!client->active)
1867 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
1869 // connect to the client
1870 // everything is allocated, just fill in the details
1871 strlcpy (conn->address, addressstring2, sizeof (conn->address));
1872 if (developer.integer)
1873 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
1874 // send back the info about the server connection
1875 SZ_Clear(&net_message);
1876 // save space for the header, filled in later
1877 MSG_WriteLong(&net_message, 0);
1878 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1879 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
1880 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1881 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1882 SZ_Clear(&net_message);
1883 // now set up the client struct
1885 SV_ConnectClient(clientnum, conn);
1887 NetConn_Heartbeat(1);
1891 //if (developer.integer)
1892 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
1893 // no room; try to let player know
1894 SZ_Clear(&net_message);
1895 // save space for the header, filled in later
1896 MSG_WriteLong(&net_message, 0);
1897 MSG_WriteByte(&net_message, CCREP_REJECT);
1898 MSG_WriteString(&net_message, "Server is full.\n");
1899 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1900 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1901 SZ_Clear(&net_message);
1908 case CCREQ_SERVER_INFO:
1909 if (developer.integer)
1910 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
1911 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
1913 if (developer.integer)
1914 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
1915 SZ_Clear(&net_message);
1916 // save space for the header, filled in later
1917 MSG_WriteLong(&net_message, 0);
1918 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
1919 UDP_GetSocketAddr(UDP_acceptSock, &newaddr);
1920 MSG_WriteString(&net_message, UDP_AddrToString(&newaddr));
1921 MSG_WriteString(&net_message, hostname.string);
1922 MSG_WriteString(&net_message, sv.name);
1923 MSG_WriteByte(&net_message, net_activeconnections);
1924 MSG_WriteByte(&net_message, svs.maxclients);
1925 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1926 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1927 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1928 SZ_Clear(&net_message);
1931 case CCREQ_PLAYER_INFO:
1932 if (developer.integer)
1933 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
1936 int playerNumber, activeNumber, clientNumber;
1939 playerNumber = MSG_ReadByte();
1941 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
1942 if (client->active && ++activeNumber == playerNumber)
1944 if (clientNumber != svs.maxclients)
1946 SZ_Clear(&net_message);
1947 // save space for the header, filled in later
1948 MSG_WriteLong(&net_message, 0);
1949 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
1950 MSG_WriteByte(&net_message, playerNumber);
1951 MSG_WriteString(&net_message, client->name);
1952 MSG_WriteLong(&net_message, client->colors);
1953 MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
1954 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
1955 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
1956 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1957 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1958 SZ_Clear(&net_message);
1962 case CCREQ_RULE_INFO:
1963 if (developer.integer)
1964 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
1970 // find the search start location
1971 prevCvarName = MSG_ReadString();
1972 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
1974 // send the response
1975 SZ_Clear(&net_message);
1976 // save space for the header, filled in later
1977 MSG_WriteLong(&net_message, 0);
1978 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
1981 MSG_WriteString(&net_message, var->name);
1982 MSG_WriteString(&net_message, var->string);
1984 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1985 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1986 SZ_Clear(&net_message);
1993 // we may not have liked the packet, but it was a valid control
1994 // packet, so we're done processing this packet now
2001 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol)) == 2)
2004 SV_ReadClientMessage();
2013 void NetConn_ServerFrame(void)
2016 lhnetaddress_t peeraddress;
2017 NetConn_UpdateSockets();
2018 for (i = 0;i < sv_numsockets;i++)
2019 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2020 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2021 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2023 // never timeout loopback connections
2024 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2026 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2027 SV_DropClient(false);
2032 void NetConn_QueryMasters(void)
2036 lhnetaddress_t masteraddress;
2037 lhnetaddress_t broadcastaddress;
2040 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2043 // 26000 is the default quake server port, servers on other ports will not
2045 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2046 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2048 for (i = 0;i < cl_numsockets;i++)
2052 // search LAN for Quake servers
2053 SZ_Clear(&net_message);
2054 // save space for the header, filled in later
2055 MSG_WriteLong(&net_message, 0);
2056 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2057 MSG_WriteString(&net_message, "QUAKE");
2058 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2059 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2060 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2061 SZ_Clear(&net_message);
2063 // search LAN for DarkPlaces servers
2064 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2066 // build the getservers message to send to the master servers
2067 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2070 for (masternum = 0;sv_masters[masternum].name;masternum++)
2072 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2075 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2080 if (!masterquerycount)
2082 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2083 M_Update_Return_Reason("No network");
2087 void NetConn_Heartbeat(int priority)
2089 lhnetaddress_t masteraddress;
2091 lhnetsocket_t *mysocket;
2093 // if it's a state change (client connected), limit next heartbeat to no
2094 // more than 30 sec in the future
2095 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2096 nextheartbeattime = realtime + 30.0;
2098 // limit heartbeatperiod to 30 to 270 second range,
2099 // lower limit is to avoid abusing master servers with excess traffic,
2100 // upper limit is to avoid timing out on the master server (which uses
2102 if (sv_heartbeatperiod.value < 30)
2103 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2104 if (sv_heartbeatperiod.value > 270)
2105 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2107 // make advertising optional and don't advertise singleplayer games, and
2108 // only send a heartbeat as often as the admin wants
2109 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2111 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2112 for (masternum = 0;sv_masters[masternum].name;masternum++)
2113 if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2114 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2118 static void Net_Heartbeat_f(void)
2121 NetConn_Heartbeat(2);
2123 Con_Print("No server running, can not heartbeat to master server.\n");
2126 void PrintStats(netconn_t *conn)
2128 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2129 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2131 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2134 void Net_Stats_f(void)
2137 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2138 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2139 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2140 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2141 Con_Printf("packetsSent = %i\n", packetsSent);
2142 Con_Printf("packetsReSent = %i\n", packetsReSent);
2143 Con_Printf("packetsReceived = %i\n", packetsReceived);
2144 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2145 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2146 Con_Print("connections =\n");
2147 for (conn = netconn_list;conn;conn = conn->next)
2151 void Net_Slist_f(void)
2153 ServerList_ResetMasks();
2154 serverlist_sortbyfield = SLIF_PING;
2155 serverlist_sortdescending = false;
2156 if (m_state != m_slist) {
2157 Con_Print("Sending requests to master servers\n");
2158 ServerList_QueryList();
2159 serverlist_consoleoutput = true;
2160 Con_Print("Listening for replies...\n");
2162 ServerList_QueryList();
2165 void NetConn_Init(void)
2168 lhnetaddress_t tempaddress;
2169 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2170 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2171 Cmd_AddCommand("net_slist", Net_Slist_f, "query master series and print all server information");
2172 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2173 Cvar_RegisterVariable(&net_slist_queriespersecond);
2174 Cvar_RegisterVariable(&net_slist_queriesperframe);
2175 Cvar_RegisterVariable(&net_slist_timeout);
2176 Cvar_RegisterVariable(&net_slist_maxtries);
2177 Cvar_RegisterVariable(&net_messagetimeout);
2178 Cvar_RegisterVariable(&net_messagerejointimeout);
2179 Cvar_RegisterVariable(&net_connecttimeout);
2180 Cvar_RegisterVariable(&cl_netlocalping);
2181 Cvar_RegisterVariable(&cl_netpacketloss);
2182 Cvar_RegisterVariable(&hostname);
2183 Cvar_RegisterVariable(&developer_networking);
2184 Cvar_RegisterVariable(&cl_netport);
2185 Cvar_RegisterVariable(&sv_netport);
2186 Cvar_RegisterVariable(&net_address);
2187 //Cvar_RegisterVariable(&net_address_ipv6);
2188 Cvar_RegisterVariable(&sv_public);
2189 Cvar_RegisterVariable(&sv_heartbeatperiod);
2190 for (i = 0;sv_masters[i].name;i++)
2191 Cvar_RegisterVariable(&sv_masters[i]);
2192 // 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.
2193 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2195 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2197 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2198 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2201 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2203 // 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
2204 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2206 i = atoi(com_argv[i + 1]);
2207 if (i >= 0 && i < 65536)
2209 Con_Printf("-port option used, setting port cvar to %i\n", i);
2210 Cvar_SetValueQuick(&sv_netport, i);
2213 Con_Printf("-port option used, but %i is not a valid port number\n", i);
2217 net_message.data = net_message_buf;
2218 net_message.maxsize = sizeof(net_message_buf);
2219 net_message.cursize = 0;
2223 void NetConn_Shutdown(void)
2225 NetConn_CloseClientPorts();
2226 NetConn_CloseServerPorts();