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 // for secure rcon authentication
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
34 // note this defaults on for dedicated servers, off for listen servers
35 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
36 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
38 static cvar_t sv_masters [] =
40 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
41 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
42 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
43 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
44 {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
45 {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
46 {0, "sv_masterextra3", "92.62.40.6", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
50 static cvar_t sv_qwmasters [] =
52 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
53 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
54 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
55 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
56 {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
57 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
58 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
59 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
60 {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
64 static double nextheartbeattime = 0;
66 sizebuf_t net_message;
67 static unsigned char net_message_buf[NET_MAXMESSAGE];
69 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
70 cvar_t net_connecttimeout = {0, "net_connecttimeout","15", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods). Must be above 10 seconds."};
71 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
72 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
73 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
75 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)"};
76 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
77 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
78 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
79 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)"};
80 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
81 static cvar_t net_slist_pause = {0, "net_slist_pause", "0", "when set to 1, the server list won't update until it is set back to 0"};
82 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)"};
83 static cvar_t net_slist_favorites = {CVAR_SAVE, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
85 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible"};
86 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode"};
87 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
88 static cvar_t rcon_secure_maxdiff = {0, "rcon_secure_maxdiff", "5", "maximum time difference between rcon request and server system clock (to protect against replay attack)"};
89 extern cvar_t rcon_secure;
91 /* statistic counters */
92 static int packetsSent = 0;
93 static int packetsReSent = 0;
94 static int packetsReceived = 0;
95 static int receivedDuplicateCount = 0;
96 static int droppedDatagrams = 0;
98 static int unreliableMessagesSent = 0;
99 static int unreliableMessagesReceived = 0;
100 static int reliableMessagesSent = 0;
101 static int reliableMessagesReceived = 0;
103 double masterquerytime = -1000;
104 int masterquerycount = 0;
105 int masterreplycount = 0;
106 int serverquerycount = 0;
107 int serverreplycount = 0;
109 // this is only false if there are still servers left to query
110 static qboolean serverlist_querysleep = true;
111 static qboolean serverlist_paused = false;
112 // this is pushed a second or two ahead of realtime whenever a master server
113 // reply is received, to avoid issuing queries while master replies are still
114 // flooding in (which would make a mess of the ping times)
115 static double serverlist_querywaittime = 0;
117 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
118 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
120 static int cl_numsockets;
121 static lhnetsocket_t *cl_sockets[16];
122 static int sv_numsockets;
123 static lhnetsocket_t *sv_sockets[16];
125 netconn_t *netconn_list = NULL;
126 mempool_t *netconn_mempool = NULL;
128 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
129 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
130 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
131 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
133 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
134 int net_extresponse_count = 0;
135 int net_extresponse_last = 0;
137 // ServerList interface
138 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
139 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
141 serverlist_infofield_t serverlist_sortbyfield;
142 int serverlist_sortflags;
144 int serverlist_viewcount = 0;
145 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
147 int serverlist_cachecount;
148 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
150 qboolean serverlist_consoleoutput;
152 // helper function to insert a value into the viewset
153 // spare entries will be removed
154 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
157 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
158 i = serverlist_viewcount++;
160 i = SERVERLIST_VIEWLISTSIZE - 1;
163 for( ; i > index ; i-- )
164 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
166 serverlist_viewlist[index] = entry;
169 // we suppose serverlist_viewcount to be valid, ie > 0
170 static void _ServerList_ViewList_Helper_Remove( int index )
172 serverlist_viewcount--;
173 for( ; index < serverlist_viewcount ; index++ )
174 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
177 // returns true if A should be inserted before B
178 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
180 int result = 0; // > 0 if for numbers A > B and for text if A < B
182 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
184 if(A->info.isfavorite != B->info.isfavorite)
185 return A->info.isfavorite;
188 switch( serverlist_sortbyfield ) {
190 result = A->info.ping - B->info.ping;
192 case SLIF_MAXPLAYERS:
193 result = A->info.maxplayers - B->info.maxplayers;
195 case SLIF_NUMPLAYERS:
196 result = A->info.numplayers - B->info.numplayers;
199 result = A->info.numbots - B->info.numbots;
202 result = A->info.numhumans - B->info.numhumans;
205 result = A->info.freeslots - B->info.freeslots;
208 result = A->info.protocol - B->info.protocol;
211 result = strcmp( B->info.cname, A->info.cname );
214 result = strcasecmp( B->info.game, A->info.game );
217 result = strcasecmp( B->info.map, A->info.map );
220 result = strcasecmp( B->info.mod, A->info.mod );
223 result = strcasecmp( B->info.name, A->info.name );
226 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
228 case SLIF_ISFAVORITE:
229 result = !!B->info.isfavorite - !!A->info.isfavorite;
232 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
238 if( serverlist_sortflags & SLSF_DESCENDING )
244 // if the chosen sort key is identical, sort by index
245 // (makes this a stable sort, so that later replies from servers won't
246 // shuffle the servers around when they have the same ping)
250 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
252 // This should actually be done with some intermediate and end-of-function return
264 case SLMO_GREATEREQUAL:
266 case SLMO_NOTCONTAIN:
267 case SLMO_STARTSWITH:
268 case SLMO_NOTSTARTSWITH:
271 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
276 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
279 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
280 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
281 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
282 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
284 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
285 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
288 // Same here, also using an intermediate & final return would be more appropriate
292 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
293 case SLMO_NOTCONTAIN:
294 return !*bufferB || !strstr( bufferA, bufferB );
295 case SLMO_STARTSWITH:
296 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
297 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
298 case SLMO_NOTSTARTSWITH:
299 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
301 return strcmp( bufferA, bufferB ) < 0;
303 return strcmp( bufferA, bufferB ) <= 0;
305 return strcmp( bufferA, bufferB ) == 0;
307 return strcmp( bufferA, bufferB ) > 0;
309 return strcmp( bufferA, bufferB ) != 0;
310 case SLMO_GREATEREQUAL:
311 return strcmp( bufferA, bufferB ) >= 0;
313 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
318 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
320 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
322 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
324 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
326 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
328 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
330 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
332 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
334 if( *mask->info.cname
335 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
338 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
341 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
344 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
347 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
349 if( *mask->info.qcstatus
350 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
352 if( *mask->info.players
353 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
355 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
360 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
365 // reject incompatible servers
366 if (entry->info.gameversion != gameversion.integer)
369 // refresh the "favorite" status
370 text = net_slist_favorites.string;
371 entry->info.isfavorite = false;
372 while(COM_ParseToken_Console(&text))
374 if(!strcmp(com_token, entry->info.cname))
376 entry->info.isfavorite = true;
381 // FIXME: change this to be more readable (...)
382 // now check whether it passes through the masks
383 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
384 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
387 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
388 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
390 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
393 if( !serverlist_viewcount ) {
394 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
397 // ok, insert it, we just need to find out where exactly:
400 // check whether to insert it as new first item
401 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
402 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
404 } // check whether to insert it as new last item
405 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
406 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
410 end = serverlist_viewcount - 1;
411 while( end > start + 1 )
413 mid = (start + end) / 2;
414 // test the item that lies in the middle between start and end
415 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
416 // the item has to be in the upper half
419 // the item has to be in the lower half
422 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
425 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
428 for( i = 0; i < serverlist_viewcount; i++ )
430 if (serverlist_viewlist[i] == entry)
432 _ServerList_ViewList_Helper_Remove(i);
438 void ServerList_RebuildViewList(void)
442 serverlist_viewcount = 0;
443 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
444 serverlist_entry_t *entry = &serverlist_cache[i];
445 // also display entries that are currently being refreshed [11/8/2007 Black]
446 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
447 ServerList_ViewList_Insert( entry );
451 void ServerList_ResetMasks(void)
455 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
456 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
457 // numbots needs to be compared to -1 to always succeed
458 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
459 serverlist_andmasks[i].info.numbots = -1;
460 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
461 serverlist_ormasks[i].info.numbots = -1;
464 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
467 int numplayers = 0, maxplayers = 0;
468 for (i = 0;i < serverlist_cachecount;i++)
470 if (serverlist_cache[i].query == SQS_QUERIED)
472 numplayers += serverlist_cache[i].info.numhumans;
473 maxplayers += serverlist_cache[i].info.maxplayers;
476 *numplayerspointer = numplayers;
477 *maxplayerspointer = maxplayers;
481 static void _ServerList_Test(void)
484 for( i = 0 ; i < 1024 ; i++ ) {
485 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
486 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
487 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
488 serverlist_cache[serverlist_cachecount].finished = true;
489 dpsnprintf( serverlist_cache[serverlist_cachecount].line1, sizeof(serverlist_cache[serverlist_cachecount].info.line1), "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
490 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
491 serverlist_cachecount++;
496 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
498 masterquerytime = realtime;
499 masterquerycount = 0;
500 masterreplycount = 0;
502 serverquerycount = 0;
503 serverreplycount = 0;
504 serverlist_cachecount = 0;
505 serverlist_viewcount = 0;
507 // refresh all entries
509 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
510 serverlist_entry_t *entry = &serverlist_cache[ n ];
511 entry->query = SQS_REFRESHING;
512 entry->querycounter = 0;
515 serverlist_consoleoutput = consoleoutput;
517 //_ServerList_Test();
519 NetConn_QueryMasters(querydp, queryqw);
524 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
526 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
530 if (cl_netpacketloss_receive.integer)
531 for (i = 0;i < cl_numsockets;i++)
532 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
534 if (developer_networking.integer)
536 char addressstring[128], addressstring2[128];
537 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
540 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
541 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
542 Com_HexDumpToConsole((unsigned char *)data, length);
545 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
550 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
554 if (cl_netpacketloss_send.integer)
555 for (i = 0;i < cl_numsockets;i++)
556 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
558 ret = LHNET_Write(mysocket, data, length, peeraddress);
559 if (developer_networking.integer)
561 char addressstring[128], addressstring2[128];
562 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
563 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
564 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
565 Com_HexDumpToConsole((unsigned char *)data, length);
570 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
572 // note this does not include the trailing NULL because we add that in the parser
573 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
576 qboolean NetConn_CanSend(netconn_t *conn)
578 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
579 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
580 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
581 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
582 if (realtime > conn->cleartime)
586 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
591 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
595 // if this packet was supposedly choked, but we find ourselves sending one
596 // anyway, make sure the size counting starts at zero
597 // (this mostly happens on level changes and disconnects and such)
598 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
599 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
601 if (protocol == PROTOCOL_QUAKEWORLD)
604 qboolean sendreliable;
606 // note that it is ok to send empty messages to the qw server,
607 // otherwise it won't respond to us at all
609 sendreliable = false;
610 // if the remote side dropped the last reliable message, resend it
611 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
613 // if the reliable transmit buffer is empty, copy the current message out
614 if (!conn->sendMessageLength && conn->message.cursize)
616 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
617 conn->sendMessageLength = conn->message.cursize;
618 SZ_Clear(&conn->message); // clear the message buffer
619 conn->qw.reliable_sequence ^= 1;
622 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
623 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
624 // last received unreliable packet number, and last received reliable packet number (0 or 1)
625 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
627 conn->outgoing_unreliable_sequence++;
628 // client sends qport in every packet
629 if (conn == cls.netcon)
631 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
633 // also update cls.qw_outgoing_sequence
634 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
636 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
638 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
642 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
644 // add the reliable message if there is one
647 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
648 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
649 packetLen += conn->sendMessageLength;
650 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
653 // add the unreliable message if possible
654 if (packetLen + data->cursize <= 1400)
656 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
657 memcpy(sendbuffer + packetLen, data->data, data->cursize);
658 packetLen += data->cursize;
661 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
664 unreliableMessagesSent++;
666 totallen += packetLen + 28;
670 unsigned int packetLen;
671 unsigned int dataLen;
673 unsigned int *header;
675 // if a reliable message fragment has been lost, send it again
676 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
678 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
680 dataLen = conn->sendMessageLength;
685 dataLen = MAX_PACKETFRAGMENT;
689 packetLen = NET_HEADERSIZE + dataLen;
691 header = (unsigned int *)sendbuffer;
692 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
693 header[1] = BigLong(conn->nq.sendSequence - 1);
694 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
696 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
698 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
700 conn->lastSendTime = realtime;
704 totallen += packetLen + 28;
707 // if we have a new reliable message to send, do so
708 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
710 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
712 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
713 conn->message.overflowed = true;
717 if (developer_networking.integer && conn == cls.netcon)
719 Con_Print("client sending reliable message to server:\n");
720 SZ_HexDumpToConsole(&conn->message);
723 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
724 conn->sendMessageLength = conn->message.cursize;
725 SZ_Clear(&conn->message);
727 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
729 dataLen = conn->sendMessageLength;
734 dataLen = MAX_PACKETFRAGMENT;
738 packetLen = NET_HEADERSIZE + dataLen;
740 header = (unsigned int *)sendbuffer;
741 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
742 header[1] = BigLong(conn->nq.sendSequence);
743 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
745 conn->nq.sendSequence++;
747 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
749 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
751 conn->lastSendTime = realtime;
753 reliableMessagesSent++;
755 totallen += packetLen + 28;
758 // if we have an unreliable message to send, do so
761 packetLen = NET_HEADERSIZE + data->cursize;
763 if (packetLen > (int)sizeof(sendbuffer))
765 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
769 header = (unsigned int *)sendbuffer;
770 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
771 header[1] = BigLong(conn->outgoing_unreliable_sequence);
772 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
774 conn->outgoing_unreliable_sequence++;
776 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
778 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
781 unreliableMessagesSent++;
783 totallen += packetLen + 28;
787 // delay later packets to obey rate limit
788 if (conn->cleartime < realtime - 0.1)
789 conn->cleartime = realtime - 0.1;
790 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
791 if (conn->cleartime < realtime)
792 conn->cleartime = realtime;
797 qboolean NetConn_HaveClientPorts(void)
799 return !!cl_numsockets;
802 qboolean NetConn_HaveServerPorts(void)
804 return !!sv_numsockets;
807 void NetConn_CloseClientPorts(void)
809 for (;cl_numsockets > 0;cl_numsockets--)
810 if (cl_sockets[cl_numsockets - 1])
811 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
814 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
816 lhnetaddress_t address;
818 char addressstring2[1024];
819 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
821 if ((s = LHNET_OpenSocket_Connectionless(&address)))
823 cl_sockets[cl_numsockets++] = s;
824 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
825 Con_Printf("Client opened a socket on address %s\n", addressstring2);
829 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
830 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
834 Con_Printf("Client unable to parse address %s\n", addressstring);
837 void NetConn_OpenClientPorts(void)
840 NetConn_CloseClientPorts();
841 port = bound(0, cl_netport.integer, 65535);
842 if (cl_netport.integer != port)
843 Cvar_SetValueQuick(&cl_netport, port);
845 Con_Printf("Client using an automatically assigned port\n");
847 Con_Printf("Client using port %i\n", port);
848 NetConn_OpenClientPort("local:2", 0);
849 NetConn_OpenClientPort(net_address.string, port);
850 //NetConn_OpenClientPort(net_address_ipv6.string, port);
853 void NetConn_CloseServerPorts(void)
855 for (;sv_numsockets > 0;sv_numsockets--)
856 if (sv_sockets[sv_numsockets - 1])
857 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
860 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
862 lhnetaddress_t address;
865 char addressstring2[1024];
867 for (port = defaultport; port <= defaultport + 100; port++)
869 if (LHNETADDRESS_FromString(&address, addressstring, port))
871 if ((s = LHNET_OpenSocket_Connectionless(&address)))
873 sv_sockets[sv_numsockets++] = s;
874 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
875 Con_Printf("Server listening on address %s\n", addressstring2);
880 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
881 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
886 Con_Printf("Server unable to parse address %s\n", addressstring);
887 // if it cant parse one address, it wont be able to parse another for sure
893 void NetConn_OpenServerPorts(int opennetports)
896 NetConn_CloseServerPorts();
897 NetConn_UpdateSockets();
898 port = bound(0, sv_netport.integer, 65535);
901 Con_Printf("Server using port %i\n", port);
902 if (sv_netport.integer != port)
903 Cvar_SetValueQuick(&sv_netport, port);
904 if (cls.state != ca_dedicated)
905 NetConn_OpenServerPort("local:1", 0);
908 NetConn_OpenServerPort(net_address.string, port);
909 //NetConn_OpenServerPort(net_address_ipv6.string, port);
911 if (sv_numsockets == 0)
912 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
915 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
917 int i, a = LHNETADDRESS_GetAddressType(address);
918 for (i = 0;i < cl_numsockets;i++)
919 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
920 return cl_sockets[i];
924 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
926 int i, a = LHNETADDRESS_GetAddressType(address);
927 for (i = 0;i < sv_numsockets;i++)
928 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
929 return sv_sockets[i];
933 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
936 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
937 conn->mysocket = mysocket;
938 conn->peeraddress = *peeraddress;
939 conn->lastMessageTime = realtime;
940 conn->message.data = conn->messagedata;
941 conn->message.maxsize = sizeof(conn->messagedata);
942 conn->message.cursize = 0;
943 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
944 // reduce effectiveness of connection request floods
945 conn->timeout = realtime + net_connecttimeout.value;
946 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
947 conn->next = netconn_list;
952 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
953 void NetConn_Close(netconn_t *conn)
956 // remove connection from list
958 // allow the client to reconnect immediately
959 NetConn_ClearConnectFlood(&(conn->peeraddress));
961 if (conn == netconn_list)
962 netconn_list = conn->next;
965 for (c = netconn_list;c;c = c->next)
969 c->next = conn->next;
973 // not found in list, we'll avoid crashing here...
981 static int clientport = -1;
982 static int clientport2 = -1;
983 static int hostport = -1;
984 void NetConn_UpdateSockets(void)
986 if (cls.state != ca_dedicated)
988 if (clientport2 != cl_netport.integer)
990 clientport2 = cl_netport.integer;
991 if (cls.state == ca_connected)
992 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
994 if (cls.state == ca_disconnected && clientport != clientport2)
996 clientport = clientport2;
997 NetConn_CloseClientPorts();
999 if (cl_numsockets == 0)
1000 NetConn_OpenClientPorts();
1003 if (hostport != sv_netport.integer)
1005 hostport = sv_netport.integer;
1007 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1011 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1013 int originallength = length;
1017 if (protocol == PROTOCOL_QUAKEWORLD)
1019 int sequence, sequence_ack;
1020 int reliable_ack, reliable_message;
1024 sequence = LittleLong(*((int *)(data + 0)));
1025 sequence_ack = LittleLong(*((int *)(data + 4)));
1029 if (conn != cls.netcon)
1034 // 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?)
1035 qport = LittleShort(*((int *)(data + 8)));
1041 reliable_message = (sequence >> 31) & 1;
1042 reliable_ack = (sequence_ack >> 31) & 1;
1043 sequence &= ~(1<<31);
1044 sequence_ack &= ~(1<<31);
1045 if (sequence <= conn->qw.incoming_sequence)
1047 //Con_DPrint("Got a stale datagram\n");
1050 count = sequence - (conn->qw.incoming_sequence + 1);
1053 droppedDatagrams += count;
1054 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1057 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1058 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1059 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1060 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1063 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1064 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1065 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1066 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1067 if (reliable_ack == conn->qw.reliable_sequence)
1069 // received, now we will be able to send another reliable message
1070 conn->sendMessageLength = 0;
1071 reliableMessagesReceived++;
1073 conn->qw.incoming_sequence = sequence;
1074 if (conn == cls.netcon)
1075 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1076 conn->qw.incoming_acknowledged = sequence_ack;
1077 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1078 if (reliable_message)
1079 conn->qw.incoming_reliable_sequence ^= 1;
1080 conn->lastMessageTime = realtime;
1081 conn->timeout = realtime + newtimeout;
1082 unreliableMessagesReceived++;
1083 SZ_Clear(&net_message);
1084 SZ_Write(&net_message, data, length);
1092 unsigned int sequence;
1095 qlength = (unsigned int)BigLong(((int *)data)[0]);
1096 flags = qlength & ~NETFLAG_LENGTH_MASK;
1097 qlength &= NETFLAG_LENGTH_MASK;
1098 // control packets were already handled
1099 if (!(flags & NETFLAG_CTL) && qlength == length)
1101 sequence = BigLong(((int *)data)[1]);
1105 if (flags & NETFLAG_UNRELIABLE)
1107 if (sequence >= conn->nq.unreliableReceiveSequence)
1109 if (sequence > conn->nq.unreliableReceiveSequence)
1111 count = sequence - conn->nq.unreliableReceiveSequence;
1112 droppedDatagrams += count;
1113 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1116 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1117 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1118 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1119 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1122 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1123 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1124 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1125 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1126 conn->nq.unreliableReceiveSequence = sequence + 1;
1127 conn->lastMessageTime = realtime;
1128 conn->timeout = realtime + newtimeout;
1129 unreliableMessagesReceived++;
1132 SZ_Clear(&net_message);
1133 SZ_Write(&net_message, data, length);
1139 // Con_DPrint("Got a stale datagram\n");
1142 else if (flags & NETFLAG_ACK)
1144 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1145 if (sequence == (conn->nq.sendSequence - 1))
1147 if (sequence == conn->nq.ackSequence)
1149 conn->nq.ackSequence++;
1150 if (conn->nq.ackSequence != conn->nq.sendSequence)
1151 Con_DPrint("ack sequencing error\n");
1152 conn->lastMessageTime = realtime;
1153 conn->timeout = realtime + newtimeout;
1154 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1156 unsigned int packetLen;
1157 unsigned int dataLen;
1159 unsigned int *header;
1161 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1162 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1164 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1166 dataLen = conn->sendMessageLength;
1171 dataLen = MAX_PACKETFRAGMENT;
1175 packetLen = NET_HEADERSIZE + dataLen;
1177 header = (unsigned int *)sendbuffer;
1178 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1179 header[1] = BigLong(conn->nq.sendSequence);
1180 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1182 conn->nq.sendSequence++;
1184 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1186 conn->lastSendTime = realtime;
1191 conn->sendMessageLength = 0;
1194 // Con_DPrint("Duplicate ACK received\n");
1197 // Con_DPrint("Stale ACK received\n");
1200 else if (flags & NETFLAG_DATA)
1202 unsigned int temppacket[2];
1203 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1204 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1205 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1206 temppacket[1] = BigLong(sequence);
1207 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1208 if (sequence == conn->nq.receiveSequence)
1210 conn->lastMessageTime = realtime;
1211 conn->timeout = realtime + newtimeout;
1212 conn->nq.receiveSequence++;
1213 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1214 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1215 conn->receiveMessageLength += length;
1217 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1218 "Dropping the message!\n", sequence );
1219 conn->receiveMessageLength = 0;
1222 if (flags & NETFLAG_EOM)
1224 reliableMessagesReceived++;
1225 length = conn->receiveMessageLength;
1226 conn->receiveMessageLength = 0;
1229 SZ_Clear(&net_message);
1230 SZ_Write(&net_message, conn->receiveMessage, length);
1237 receivedDuplicateCount++;
1245 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1247 cls.connect_trying = false;
1248 M_Update_Return_Reason("");
1249 // the connection request succeeded, stop current connection and set up a new connection
1251 // if we're connecting to a remote server, shut down any local server
1252 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1253 Host_ShutdownServer ();
1254 // allocate a net connection to keep track of things
1255 cls.netcon = NetConn_Open(mysocket, peeraddress);
1256 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1257 key_dest = key_game;
1259 cls.demonum = -1; // not in the demo loop now
1260 cls.state = ca_connected;
1261 cls.signon = 0; // need all the signon messages before playing
1262 cls.protocol = initialprotocol;
1263 // reset move sequence numbering on this new connection
1264 cls.servermovesequence = 0;
1265 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1266 Cmd_ForwardStringToServer("new");
1267 if (cls.protocol == PROTOCOL_QUAKE)
1269 // write a keepalive (clc_nop) as it seems to greatly improve the
1270 // chances of connecting to a netquake server
1272 unsigned char buf[4];
1273 memset(&msg, 0, sizeof(msg));
1275 msg.maxsize = sizeof(buf);
1276 MSG_WriteChar(&msg, clc_nop);
1277 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1281 int NetConn_IsLocalGame(void)
1283 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1288 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1292 serverlist_entry_t *entry = NULL;
1294 // search the cache for this server and update it
1295 for (n = 0;n < serverlist_cachecount;n++) {
1296 entry = &serverlist_cache[ n ];
1297 if (!strcmp(addressstring, entry->info.cname))
1301 if (n == serverlist_cachecount)
1303 // LAN search doesnt require an answer from the master server so we wont
1304 // know the ping nor will it be initialized already...
1307 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1310 entry = &serverlist_cache[n];
1312 memset(entry, 0, sizeof(*entry));
1313 // store the data the engine cares about (address and ping)
1314 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1315 entry->info.ping = 100000;
1316 entry->querytime = realtime;
1317 // if not in the slist menu we should print the server to console
1318 if (serverlist_consoleoutput)
1319 Con_Printf("querying %s\n", addressstring);
1320 ++serverlist_cachecount;
1323 // we should not NEED this part...
1324 text = net_slist_favorites.string;
1325 while(COM_ParseToken_Console(&text))
1327 if(!strcmp(com_token, addressstring))
1328 entry->isfavorite = 1;
1332 // if this is the first reply from this server, count it as having replied
1333 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1334 pingtime = bound(0, pingtime, 9999);
1335 if (entry->query == SQS_REFRESHING) {
1336 entry->info.ping = pingtime;
1337 entry->query = SQS_QUERIED;
1339 // convert to unsigned to catch the -1
1340 // I still dont like this but its better than the old 10000 magic ping number - as in easier to type and read :( [11/8/2007 Black]
1341 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1345 // other server info is updated by the caller
1349 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1351 serverlist_entry_t *entry = &serverlist_cache[n];
1352 serverlist_info_t *info = &entry->info;
1353 // update description strings for engine menu and console output
1354 dpsnprintf(entry->line1, sizeof(serverlist_cache[n].line1), "^%c%5d^7 ^%c%3u^7/%3u %-65.65s", info->ping >= 300 ? '1' : (info->ping >= 200 ? '3' : '7'), (int)info->ping, ((info->numhumans > 0 && info->numhumans < info->maxplayers) ? (info->numhumans >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1355 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
1356 if (entry->query == SQS_QUERIED)
1358 if(!serverlist_paused)
1359 ServerList_ViewList_Remove(entry);
1361 // if not in the slist menu we should print the server to console (if wanted)
1362 else if( serverlist_consoleoutput )
1363 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1364 // and finally, update the view set
1365 if(!serverlist_paused)
1366 ServerList_ViewList_Insert( entry );
1367 // update the entry's state
1368 serverlist_cache[n].query = SQS_QUERIED;
1371 // returns true, if it's sensible to continue the processing
1372 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1374 serverlist_entry_t *entry;
1376 // ignore the rest of the message if the serverlist is full
1377 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1379 // also ignore it if we have already queried it (other master server response)
1380 for( n = 0 ; n < serverlist_cachecount ; n++ )
1381 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1384 entry = &serverlist_cache[n];
1386 if( n < serverlist_cachecount ) {
1387 // the entry has already been queried once or
1391 memset(entry, 0, sizeof(entry));
1392 entry->protocol = protocol;
1393 // store the data the engine cares about (address and ping)
1394 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1396 entry->info.isfavorite = isfavorite;
1398 // no, then reset the ping right away
1399 entry->info.ping = -1;
1400 // we also want to increase the serverlist_cachecount then
1401 serverlist_cachecount++;
1404 entry->query = SQS_QUERYING;
1409 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1411 qboolean fromserver;
1412 int ret, c, control;
1414 char *string, addressstring2[128], ipstring[32];
1415 char stringbuf[16384];
1417 // quakeworld ingame packet
1418 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1420 // convert the address to a string incase we need it
1421 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1423 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1425 // received a command string - strip off the packaging and put it
1426 // into our string buffer with NULL termination
1429 length = min(length, (int)sizeof(stringbuf) - 1);
1430 memcpy(stringbuf, data, length);
1431 stringbuf[length] = 0;
1434 if (developer_networking.integer)
1436 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1437 Com_HexDumpToConsole(data, length);
1440 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1442 // darkplaces or quake3
1443 char protocolnames[1400];
1444 Protocol_Names(protocolnames, sizeof(protocolnames));
1445 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1446 M_Update_Return_Reason("Got challenge response");
1447 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1448 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1449 // TODO: add userinfo stuff here instead of using NQ commands?
1450 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1453 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1455 // darkplaces or quake3
1456 M_Update_Return_Reason("Accepted");
1457 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1460 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1462 char rejectreason[32];
1463 cls.connect_trying = false;
1465 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1466 memcpy(rejectreason, string, length);
1467 rejectreason[length] = 0;
1468 M_Update_Return_Reason(rejectreason);
1471 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1473 serverlist_info_t *info;
1478 // search the cache for this server and update it
1479 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1483 info = &serverlist_cache[n].info;
1488 info->qcstatus[0] = 0;
1489 info->players[0] = 0;
1490 info->protocol = -1;
1491 info->numplayers = 0;
1493 info->maxplayers = 0;
1494 info->gameversion = 0;
1496 p = strchr(string, '\n');
1499 *p = 0; // cut off the string there
1503 Con_Printf("statusResponse without players block?\n");
1505 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1506 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1507 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1508 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1509 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1510 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1511 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1512 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1513 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1514 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1515 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1516 info->numhumans = info->numplayers - max(0, info->numbots);
1517 info->freeslots = info->maxplayers - info->numplayers;
1519 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1523 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1525 serverlist_info_t *info;
1529 // search the cache for this server and update it
1530 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1534 info = &serverlist_cache[n].info;
1539 info->qcstatus[0] = 0;
1540 info->players[0] = 0;
1541 info->protocol = -1;
1542 info->numplayers = 0;
1544 info->maxplayers = 0;
1545 info->gameversion = 0;
1547 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1548 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1549 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1550 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1551 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1552 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1553 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1554 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1555 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1556 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1557 info->numhumans = info->numplayers - max(0, info->numbots);
1558 info->freeslots = info->maxplayers - info->numplayers;
1560 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1564 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1566 // Extract the IP addresses
1570 if (serverlist_consoleoutput)
1571 Con_Print("received DarkPlaces server list...\n");
1572 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1574 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1575 if (serverlist_consoleoutput && developer_networking.integer)
1576 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1578 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1582 // move on to next address in packet
1586 // begin or resume serverlist queries
1587 serverlist_querysleep = false;
1588 serverlist_querywaittime = realtime + 3;
1591 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1593 // Extract the IP addresses
1597 if (serverlist_consoleoutput)
1598 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1599 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1601 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1602 if (serverlist_consoleoutput && developer_networking.integer)
1603 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1605 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1609 // move on to next address in packet
1613 // begin or resume serverlist queries
1614 serverlist_querysleep = false;
1615 serverlist_querywaittime = realtime + 3;
1618 if (!strncmp(string, "extResponse ", 12))
1620 ++net_extresponse_count;
1621 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1622 net_extresponse_count = NET_EXTRESPONSE_MAX;
1623 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1624 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1627 if (!strncmp(string, "ping", 4))
1629 if (developer.integer >= 10)
1630 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1631 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1634 if (!strncmp(string, "ack", 3))
1636 // QuakeWorld compatibility
1637 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1639 // challenge message
1640 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1641 M_Update_Return_Reason("Got QuakeWorld challenge response");
1642 cls.qw_qport = qport.integer;
1643 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1644 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1645 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1648 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1651 M_Update_Return_Reason("QuakeWorld Accepted");
1652 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1655 if (length > 2 && !memcmp(string, "n\\", 2))
1657 serverlist_info_t *info;
1661 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1662 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1665 // search the cache for this server and update it
1666 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1670 info = &serverlist_cache[n].info;
1671 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1672 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1673 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1674 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1676 info->numplayers = 0; // updated below
1677 info->numhumans = 0; // updated below
1678 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1679 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1681 // count active players on server
1682 // (we could gather more info, but we're just after the number)
1683 s = strchr(string, '\n');
1687 while (s < string + length)
1689 for (;s < string + length && *s != '\n';s++)
1691 if (s >= string + length)
1699 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1703 if (string[0] == 'n')
1706 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1708 // we may not have liked the packet, but it was a command packet, so
1709 // we're done processing this packet now
1712 // quakeworld ingame packet
1713 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1716 CL_ParseServerMessage();
1719 // netquake control packets, supported for compatibility only
1720 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1723 serverlist_info_t *info;
1727 SZ_Clear(&net_message);
1728 SZ_Write(&net_message, data, length);
1734 if (developer.integer >= 10)
1735 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1736 if (cls.connect_trying)
1738 lhnetaddress_t clientportaddress;
1739 clientportaddress = *peeraddress;
1740 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1741 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1742 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1743 M_Update_Return_Reason("Accepted");
1744 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1748 if (developer.integer >= 10)
1749 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1750 cls.connect_trying = false;
1751 M_Update_Return_Reason((char *)MSG_ReadString());
1753 case CCREP_SERVER_INFO:
1754 if (developer.integer >= 10)
1755 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1756 // LordHavoc: because the quake server may report weird addresses
1757 // we just ignore it and keep the real address
1759 // search the cache for this server and update it
1760 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1764 info = &serverlist_cache[n].info;
1765 strlcpy(info->game, "Quake", sizeof(info->game));
1766 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1767 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1768 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1769 info->numplayers = MSG_ReadByte();
1770 info->maxplayers = MSG_ReadByte();
1771 info->protocol = MSG_ReadByte();
1773 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1776 case CCREP_PLAYER_INFO:
1777 // we got a CCREP_PLAYER_INFO??
1778 //if (developer.integer >= 10)
1779 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1781 case CCREP_RULE_INFO:
1782 // we got a CCREP_RULE_INFO??
1783 //if (developer.integer >= 10)
1784 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1789 SZ_Clear(&net_message);
1790 // we may not have liked the packet, but it was a valid control
1791 // packet, so we're done processing this packet now
1795 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1796 CL_ParseServerMessage();
1800 void NetConn_QueryQueueFrame(void)
1806 static double querycounter = 0;
1808 if(!net_slist_pause.integer && serverlist_paused)
1809 ServerList_RebuildViewList();
1810 serverlist_paused = net_slist_pause.integer;
1812 if (serverlist_querysleep)
1815 // apply a cool down time after master server replies,
1816 // to avoid messing up the ping times on the servers
1817 if (serverlist_querywaittime > realtime)
1820 // each time querycounter reaches 1.0 issue a query
1821 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1822 maxqueries = (int)querycounter;
1823 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1824 querycounter -= maxqueries;
1826 if( maxqueries == 0 ) {
1830 // scan serverlist and issue queries as needed
1831 serverlist_querysleep = true;
1833 timeouttime = realtime - net_slist_timeout.value;
1834 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1836 serverlist_entry_t *entry = &serverlist_cache[ index ];
1837 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1842 serverlist_querysleep = false;
1843 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1848 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1850 lhnetaddress_t address;
1853 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1854 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1856 for (socket = 0; socket < cl_numsockets ; socket++)
1857 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1861 for (socket = 0; socket < cl_numsockets ; socket++)
1862 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1865 // update the entry fields
1866 entry->querytime = realtime;
1867 entry->querycounter++;
1869 // if not in the slist menu we should print the server to console
1870 if (serverlist_consoleoutput)
1871 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1877 // have we tried to refresh this server?
1878 if( entry->query == SQS_REFRESHING ) {
1879 // yes, so update the reply count (since its not responding anymore)
1881 if(!serverlist_paused)
1882 ServerList_ViewList_Remove(entry);
1884 entry->query = SQS_TIMEDOUT;
1889 void NetConn_ClientFrame(void)
1892 lhnetaddress_t peeraddress;
1893 NetConn_UpdateSockets();
1894 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1896 if (cls.connect_remainingtries == 0)
1897 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1898 cls.connect_nextsendtime = realtime + 1;
1899 cls.connect_remainingtries--;
1900 if (cls.connect_remainingtries <= -10)
1902 cls.connect_trying = false;
1903 M_Update_Return_Reason("Connect: Failed");
1906 // try challenge first (newer DP server or QW)
1907 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1908 // then try netquake as a fallback (old server, or netquake)
1909 SZ_Clear(&net_message);
1910 // save space for the header, filled in later
1911 MSG_WriteLong(&net_message, 0);
1912 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1913 MSG_WriteString(&net_message, "QUAKE");
1914 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1915 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1916 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1917 SZ_Clear(&net_message);
1919 for (i = 0;i < cl_numsockets;i++)
1920 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1921 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1922 NetConn_QueryQueueFrame();
1923 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1925 Con_Print("Connection timed out\n");
1927 Host_ShutdownServer ();
1931 #define MAX_CHALLENGES 128
1934 lhnetaddress_t address;
1938 challenge[MAX_CHALLENGES];
1940 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1944 for (i = 0;i < bufferlength - 1;i++)
1948 c = rand () % (127 - 33) + 33;
1949 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1955 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
1956 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1959 unsigned int nb_clients = 0, nb_bots = 0, i;
1965 // How many clients are there?
1966 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1968 if (svs.clients[i].active)
1971 if (!svs.clients[i].netconnection)
1977 if(prog->globaloffsets.worldstatus >= 0)
1979 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
1985 for(q = str; *q; ++q)
1986 if(*q != '\\' && *q != '\n')
1992 // TODO: we should add more information for the full status string
1993 length = dpsnprintf(out_msg, out_size,
1994 "\377\377\377\377%s\x0A"
1995 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1996 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2000 fullstatus ? "statusResponse" : "infoResponse",
2001 gamename, com_modname, gameversion.integer, svs.maxclients,
2002 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2003 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2004 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2005 fullstatus ? "\n" : "");
2007 // Make sure it fits in the buffer
2017 savelength = length;
2019 ptr = out_msg + length;
2020 left = (int)out_size - length;
2022 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2024 client_t *cl = &svs.clients[i];
2027 int nameind, cleanind, pingvalue;
2029 char cleanname [sizeof(cl->name)];
2031 // Remove all characters '"' and '\' in the player name
2036 curchar = cl->name[nameind++];
2037 if (curchar != '"' && curchar != '\\')
2039 cleanname[cleanind++] = curchar;
2040 if (cleanind == sizeof(cleanname) - 1)
2043 } while (curchar != '\0');
2044 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2046 pingvalue = (int)(cl->ping * 1000.0f);
2047 if(cl->netconnection)
2048 pingvalue = bound(1, pingvalue, 9999);
2053 if(prog->fieldoffsets.clientstatus >= 0)
2055 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2061 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2062 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2068 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2070 if(cl->frags == -666) // spectator
2071 strlcpy(teambuf, " 0", sizeof(teambuf));
2072 else if(cl->colors == 0x44) // red team
2073 strlcpy(teambuf, " 1", sizeof(teambuf));
2074 else if(cl->colors == 0xDD) // blue team
2075 strlcpy(teambuf, " 2", sizeof(teambuf));
2076 else if(cl->colors == 0xCC) // yellow team
2077 strlcpy(teambuf, " 3", sizeof(teambuf));
2078 else if(cl->colors == 0x99) // pink team
2079 strlcpy(teambuf, " 4", sizeof(teambuf));
2081 strlcpy(teambuf, " 0", sizeof(teambuf));
2086 // note: team number is inserted according to SoF2 protocol
2088 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2094 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2103 // turn it into an infoResponse!
2104 out_msg[savelength] = 0;
2105 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2106 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2123 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2125 int floodslotnum, bestfloodslotnum;
2126 double bestfloodtime;
2127 lhnetaddress_t noportpeeraddress;
2128 // see if this is a connect flood
2129 noportpeeraddress = *peeraddress;
2130 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2131 bestfloodslotnum = 0;
2132 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2133 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2135 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2137 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2138 bestfloodslotnum = floodslotnum;
2140 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2142 // this address matches an ongoing flood address
2143 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2145 // renew the ban on this address so it does not expire
2146 // until the flood has subsided
2147 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2148 //Con_Printf("Flood detected!\n");
2151 // the flood appears to have subsided, so allow this
2152 bestfloodslotnum = floodslotnum; // reuse the same slot
2156 // begin a new timeout on this address
2157 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2158 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2159 //Con_Printf("Flood detection initiated!\n");
2163 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2166 lhnetaddress_t noportpeeraddress;
2167 // see if this is a connect flood
2168 noportpeeraddress = *peeraddress;
2169 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2170 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2172 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2174 // this address matches an ongoing flood address
2176 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2177 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2178 //Con_Printf("Flood cleared!\n");
2183 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2185 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2190 t1 = (long) time(NULL);
2191 t2 = strtol(s, NULL, 0);
2192 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2195 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2198 return !memcmp(mdfourbuf, hash, 16);
2201 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2203 return !strcmp(password, hash);
2206 // returns a string describing the user level, or NULL for auth failure
2207 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2212 if(comparator(rcon_password.string, password, cs, cslen))
2215 if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2218 for(text = s; text != endpos; ++text)
2219 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2220 return NULL; // block possible exploits against the parser/alias expansion
2224 size_t l = strlen(s);
2227 hasquotes = (strchr(s, '"') != NULL);
2228 // sorry, we can't allow these substrings in wildcard expressions,
2229 // as they can mess with the argument counts
2230 text = rcon_restricted_commands.string;
2231 while(COM_ParseToken_Console(&text))
2233 // com_token now contains a pattern to check for...
2234 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2237 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2240 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2242 if(!strcmp(com_token, s))
2245 else // single-arg expression? must match the beginning of the command
2247 if(!strcmp(com_token, s))
2249 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2253 // if we got here, nothing matched!
2260 return "restricted rcon";
2263 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2267 // looks like a legitimate rcon command with the correct password
2268 const char *s_ptr = s;
2269 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2270 while(s_ptr != endpos)
2272 size_t l = strlen(s_ptr);
2274 Con_Printf(" %s;", s_ptr);
2279 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2280 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2283 size_t l = strlen(s);
2286 client_t *host_client_save = host_client;
2287 Cmd_ExecuteString(s, src_command);
2288 host_client = host_client_save;
2289 // in case it is a command that changes host_client (like restart)
2293 Con_Rcon_Redirect_End();
2297 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2301 extern void SV_SendServerinfo (client_t *client);
2302 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2304 int i, ret, clientnum, best;
2307 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2308 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2313 // convert the address to a string incase we need it
2314 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2316 // see if we can identify the sender as a local player
2317 // (this is necessary for rcon to send a reliable reply if the client is
2318 // actually on the server, not sending remotely)
2319 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2320 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2322 if (i == svs.maxclients)
2325 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2327 // received a command string - strip off the packaging and put it
2328 // into our string buffer with NULL termination
2331 length = min(length, (int)sizeof(stringbuf) - 1);
2332 memcpy(stringbuf, data, length);
2333 stringbuf[length] = 0;
2336 if (developer.integer >= 10)
2338 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2339 Com_HexDumpToConsole(data, length);
2342 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2344 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2346 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2348 if (besttime > challenge[i].time)
2349 besttime = challenge[best = i].time;
2351 // if we did not find an exact match, choose the oldest and
2352 // update address and string
2353 if (i == MAX_CHALLENGES)
2356 challenge[i].address = *peeraddress;
2357 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2359 challenge[i].time = realtime;
2360 // send the challenge
2361 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2364 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2369 if (!(s = SearchInfostring(string, "challenge")))
2371 // validate the challenge
2372 for (i = 0;i < MAX_CHALLENGES;i++)
2373 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2375 // if the challenge is not recognized, drop the packet
2376 if (i == MAX_CHALLENGES)
2379 // check engine protocol
2380 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2382 if (developer.integer >= 10)
2383 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2384 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2388 // see if this is a duplicate connection request or a disconnected
2389 // client who is rejoining to the same client slot
2390 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2392 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2394 // this is a known client...
2395 if (client->spawned)
2397 // client crashed and is coming back,
2398 // keep their stuff intact
2399 if (developer.integer >= 10)
2400 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2401 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2403 SV_SendServerinfo(client);
2408 // client is still trying to connect,
2409 // so we send a duplicate reply
2410 if (developer.integer >= 10)
2411 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2412 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2418 if (NetConn_PreventConnectFlood(peeraddress))
2421 // find an empty client slot for this new client
2422 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2425 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2427 // allocated connection
2428 if (developer.integer >= 10)
2429 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2430 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2431 // now set up the client
2433 SV_ConnectClient(clientnum, conn);
2435 NetConn_Heartbeat(1);
2440 // no empty slots found - server is full
2441 if (developer.integer >= 10)
2442 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2443 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2447 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2449 const char *challenge = NULL;
2451 // If there was a challenge in the getinfo message
2452 if (length > 8 && string[7] == ' ')
2453 challenge = string + 8;
2455 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2457 if (developer.integer >= 10)
2458 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2459 NetConn_WriteString(mysocket, response, peeraddress);
2463 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2465 const char *challenge = NULL;
2467 // If there was a challenge in the getinfo message
2468 if (length > 10 && string[9] == ' ')
2469 challenge = string + 10;
2471 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2473 if (developer.integer >= 10)
2474 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2475 NetConn_WriteString(mysocket, response, peeraddress);
2479 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2481 char *password = string + 20;
2482 char *timeval = string + 37;
2483 char *s = strchr(timeval, ' ');
2484 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2485 const char *userlevel;
2487 return true; // invalid packet
2490 userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2491 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2494 if (length >= 5 && !memcmp(string, "rcon ", 5))
2497 char *s = string + 5;
2498 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2501 if(rcon_secure.integer)
2504 for (i = 0;!ISWHITESPACE(*s);s++)
2505 if (i < (int)sizeof(password) - 1)
2507 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2510 if (!ISWHITESPACE(password[0]))
2512 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2513 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2517 if (!strncmp(string, "ping", 4))
2519 if (developer.integer >= 10)
2520 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2521 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2524 if (!strncmp(string, "ack", 3))
2526 // we may not have liked the packet, but it was a command packet, so
2527 // we're done processing this packet now
2530 // netquake control packets, supported for compatibility only, and only
2531 // when running game protocols that are normally served via this connection
2533 // (this protects more modern protocols against being used for
2534 // Quake packet flood Denial Of Service attacks)
2535 if (length >= 5 && (i = BigLong(*((int *)data))) && (i & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (i & NETFLAG_LENGTH_MASK) == length && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3))
2539 const char *protocolname;
2542 SZ_Clear(&net_message);
2543 SZ_Write(&net_message, data, length);
2549 if (developer.integer >= 10)
2550 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2551 if(!islocal && sv_public.integer <= -2)
2554 protocolname = MSG_ReadString();
2555 protocolnumber = MSG_ReadByte();
2556 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2558 if (developer.integer >= 10)
2559 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2560 SZ_Clear(&net_message);
2561 // save space for the header, filled in later
2562 MSG_WriteLong(&net_message, 0);
2563 MSG_WriteByte(&net_message, CCREP_REJECT);
2564 MSG_WriteString(&net_message, "Incompatible version.\n");
2565 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2566 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2567 SZ_Clear(&net_message);
2571 // see if this connect request comes from a known client
2572 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2574 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2576 // this is either a duplicate connection request
2577 // or coming back from a timeout
2578 // (if so, keep their stuff intact)
2581 if (developer.integer >= 10)
2582 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2583 SZ_Clear(&net_message);
2584 // save space for the header, filled in later
2585 MSG_WriteLong(&net_message, 0);
2586 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2587 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2588 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2589 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2590 SZ_Clear(&net_message);
2592 // if client is already spawned, re-send the
2593 // serverinfo message as they'll need it to play
2594 if (client->spawned)
2597 SV_SendServerinfo(client);
2604 // this is a new client, check for connection flood
2605 if (NetConn_PreventConnectFlood(peeraddress))
2608 // find a slot for the new client
2609 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2612 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2614 // connect to the client
2615 // everything is allocated, just fill in the details
2616 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2617 if (developer.integer >= 10)
2618 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2619 // send back the info about the server connection
2620 SZ_Clear(&net_message);
2621 // save space for the header, filled in later
2622 MSG_WriteLong(&net_message, 0);
2623 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2624 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2625 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2626 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2627 SZ_Clear(&net_message);
2628 // now set up the client struct
2630 SV_ConnectClient(clientnum, conn);
2632 NetConn_Heartbeat(1);
2637 if (developer.integer >= 10)
2638 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2639 // no room; try to let player know
2640 SZ_Clear(&net_message);
2641 // save space for the header, filled in later
2642 MSG_WriteLong(&net_message, 0);
2643 MSG_WriteByte(&net_message, CCREP_REJECT);
2644 MSG_WriteString(&net_message, "Server is full.\n");
2645 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2646 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2647 SZ_Clear(&net_message);
2649 case CCREQ_SERVER_INFO:
2650 if (developer.integer >= 10)
2651 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2652 if(!islocal && sv_public.integer <= -1)
2654 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2657 char myaddressstring[128];
2658 if (developer.integer >= 10)
2659 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2660 SZ_Clear(&net_message);
2661 // save space for the header, filled in later
2662 MSG_WriteLong(&net_message, 0);
2663 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2664 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2665 MSG_WriteString(&net_message, myaddressstring);
2666 MSG_WriteString(&net_message, hostname.string);
2667 MSG_WriteString(&net_message, sv.name);
2668 // How many clients are there?
2669 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2670 if (svs.clients[i].active)
2672 MSG_WriteByte(&net_message, numclients);
2673 MSG_WriteByte(&net_message, svs.maxclients);
2674 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2675 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2676 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2677 SZ_Clear(&net_message);
2680 case CCREQ_PLAYER_INFO:
2681 if (developer.integer >= 10)
2682 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2683 if(!islocal && sv_public.integer <= -1)
2687 int playerNumber, activeNumber, clientNumber;
2690 playerNumber = MSG_ReadByte();
2692 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2693 if (client->active && ++activeNumber == playerNumber)
2695 if (clientNumber != svs.maxclients)
2697 SZ_Clear(&net_message);
2698 // save space for the header, filled in later
2699 MSG_WriteLong(&net_message, 0);
2700 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2701 MSG_WriteByte(&net_message, playerNumber);
2702 MSG_WriteString(&net_message, client->name);
2703 MSG_WriteLong(&net_message, client->colors);
2704 MSG_WriteLong(&net_message, client->frags);
2705 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2706 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2707 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2708 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2709 SZ_Clear(&net_message);
2713 case CCREQ_RULE_INFO:
2714 if (developer.integer >= 10)
2715 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2716 if(!islocal && sv_public.integer <= -1)
2723 // find the search start location
2724 prevCvarName = MSG_ReadString();
2725 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2727 // send the response
2728 SZ_Clear(&net_message);
2729 // save space for the header, filled in later
2730 MSG_WriteLong(&net_message, 0);
2731 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2734 MSG_WriteString(&net_message, var->name);
2735 MSG_WriteString(&net_message, var->string);
2737 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2738 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2739 SZ_Clear(&net_message);
2745 SZ_Clear(&net_message);
2746 // we may not have liked the packet, but it was a valid control
2747 // packet, so we're done processing this packet now
2752 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2755 SV_ReadClientMessage();
2763 void NetConn_ServerFrame(void)
2766 lhnetaddress_t peeraddress;
2767 for (i = 0;i < sv_numsockets;i++)
2768 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2769 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2770 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2772 // never timeout loopback connections
2773 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2775 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2777 SV_DropClient(false);
2783 void NetConn_SleepMicroseconds(int microseconds)
2785 LHNET_SleepUntilPacket_Microseconds(microseconds);
2788 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2792 lhnetaddress_t masteraddress;
2793 lhnetaddress_t broadcastaddress;
2794 lhnetaddress_t serveraddress;
2798 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2801 // 26000 is the default quake server port, servers on other ports will not
2803 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2804 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2808 for (i = 0;i < cl_numsockets;i++)
2812 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2814 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2816 // search LAN for Quake servers
2817 SZ_Clear(&net_message);
2818 // save space for the header, filled in later
2819 MSG_WriteLong(&net_message, 0);
2820 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2821 MSG_WriteString(&net_message, "QUAKE");
2822 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2823 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2824 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2825 SZ_Clear(&net_message);
2827 // search LAN for DarkPlaces servers
2828 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2831 // build the getservers message to send to the dpmaster master servers
2832 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2835 for (masternum = 0;sv_masters[masternum].name;masternum++)
2837 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2840 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2844 // search favorite servers
2845 text = net_slist_favorites.string;
2846 while(COM_ParseToken_Console(&text))
2848 if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2850 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, com_token, true );
2857 // only query QuakeWorld servers when the user wants to
2860 for (i = 0;i < cl_numsockets;i++)
2864 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2866 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2868 // search LAN for QuakeWorld servers
2869 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2871 // build the getservers message to send to the qwmaster master servers
2872 // note this has no -1 prefix, and the trailing nul byte is sent
2873 dpsnprintf(request, sizeof(request), "c\n");
2877 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2879 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2881 if (m_state != m_slist)
2883 char lookupstring[128];
2884 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2885 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2888 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2892 // search favorite servers
2893 text = net_slist_favorites.string;
2894 while(COM_ParseToken_Console(&text))
2896 if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2898 // writing AND querying to catch replies for both
2899 // protocols (in case DP has been queried above, this
2900 // would only try the DP protocol otherwise)
2901 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &serveraddress);
2902 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, com_token, true );
2908 if (!masterquerycount)
2910 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2911 M_Update_Return_Reason("No network");
2915 void NetConn_Heartbeat(int priority)
2917 lhnetaddress_t masteraddress;
2919 lhnetsocket_t *mysocket;
2921 // if it's a state change (client connected), limit next heartbeat to no
2922 // more than 30 sec in the future
2923 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2924 nextheartbeattime = realtime + 30.0;
2926 // limit heartbeatperiod to 30 to 270 second range,
2927 // lower limit is to avoid abusing master servers with excess traffic,
2928 // upper limit is to avoid timing out on the master server (which uses
2930 if (sv_heartbeatperiod.value < 30)
2931 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2932 if (sv_heartbeatperiod.value > 270)
2933 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2935 // make advertising optional and don't advertise singleplayer games, and
2936 // only send a heartbeat as often as the admin wants
2937 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2939 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2940 for (masternum = 0;sv_masters[masternum].name;masternum++)
2941 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2942 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2946 static void Net_Heartbeat_f(void)
2949 NetConn_Heartbeat(2);
2951 Con_Print("No server running, can not heartbeat to master server.\n");
2954 void PrintStats(netconn_t *conn)
2956 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2957 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
2959 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2962 void Net_Stats_f(void)
2965 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2966 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2967 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2968 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2969 Con_Printf("packetsSent = %i\n", packetsSent);
2970 Con_Printf("packetsReSent = %i\n", packetsReSent);
2971 Con_Printf("packetsReceived = %i\n", packetsReceived);
2972 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2973 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2974 Con_Print("connections =\n");
2975 for (conn = netconn_list;conn;conn = conn->next)
2979 void Net_Refresh_f(void)
2981 if (m_state != m_slist) {
2982 Con_Print("Sending new requests to master servers\n");
2983 ServerList_QueryList(false, true, false, true);
2984 Con_Print("Listening for replies...\n");
2986 ServerList_QueryList(false, true, false, false);
2989 void Net_Slist_f(void)
2991 ServerList_ResetMasks();
2992 serverlist_sortbyfield = SLIF_PING;
2993 serverlist_sortflags = 0;
2994 if (m_state != m_slist) {
2995 Con_Print("Sending requests to master servers\n");
2996 ServerList_QueryList(true, true, false, true);
2997 Con_Print("Listening for replies...\n");
2999 ServerList_QueryList(true, true, false, false);
3002 void Net_SlistQW_f(void)
3004 ServerList_ResetMasks();
3005 serverlist_sortbyfield = SLIF_PING;
3006 serverlist_sortflags = 0;
3007 if (m_state != m_slist) {
3008 Con_Print("Sending requests to master servers\n");
3009 ServerList_QueryList(true, false, true, true);
3010 serverlist_consoleoutput = true;
3011 Con_Print("Listening for replies...\n");
3013 ServerList_QueryList(true, false, true, false);
3016 void NetConn_Init(void)
3019 lhnetaddress_t tempaddress;
3020 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3021 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3022 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3023 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3024 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3025 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3026 Cvar_RegisterVariable(&rcon_restricted_password);
3027 Cvar_RegisterVariable(&rcon_restricted_commands);
3028 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3029 Cvar_RegisterVariable(&net_slist_queriespersecond);
3030 Cvar_RegisterVariable(&net_slist_queriesperframe);
3031 Cvar_RegisterVariable(&net_slist_timeout);
3032 Cvar_RegisterVariable(&net_slist_maxtries);
3033 Cvar_RegisterVariable(&net_slist_favorites);
3034 Cvar_RegisterVariable(&net_slist_pause);
3035 Cvar_RegisterVariable(&net_messagetimeout);
3036 Cvar_RegisterVariable(&net_connecttimeout);
3037 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3038 Cvar_RegisterVariable(&cl_netlocalping);
3039 Cvar_RegisterVariable(&cl_netpacketloss_send);
3040 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3041 Cvar_RegisterVariable(&hostname);
3042 Cvar_RegisterVariable(&developer_networking);
3043 Cvar_RegisterVariable(&cl_netport);
3044 Cvar_RegisterVariable(&sv_netport);
3045 Cvar_RegisterVariable(&net_address);
3046 //Cvar_RegisterVariable(&net_address_ipv6);
3047 Cvar_RegisterVariable(&sv_public);
3048 Cvar_RegisterVariable(&sv_heartbeatperiod);
3049 for (i = 0;sv_masters[i].name;i++)
3050 Cvar_RegisterVariable(&sv_masters[i]);
3051 Cvar_RegisterVariable(&gameversion);
3052 // 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.
3053 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3055 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3057 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3058 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3061 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3063 // 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
3064 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3066 i = atoi(com_argv[i + 1]);
3067 if (i >= 0 && i < 65536)
3069 Con_Printf("-port option used, setting port cvar to %i\n", i);
3070 Cvar_SetValueQuick(&sv_netport, i);
3073 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3077 net_message.data = net_message_buf;
3078 net_message.maxsize = sizeof(net_message_buf);
3079 net_message.cursize = 0;
3083 void NetConn_Shutdown(void)
3085 NetConn_CloseClientPorts();
3086 NetConn_CloseServerPorts();