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.
27 // for secure rcon authentication
32 #define QWMASTER_PORT 27000
33 #define DPMASTER_PORT 27950
35 // note this defaults on for dedicated servers, off for listen servers
36 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; -3: already block at getchallenge level"};
37 cvar_t sv_public_rejectreason = {0, "sv_public_rejectreason", "The server is closing.", "Rejection reason for connects when sv_public is -2"};
38 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
39 extern cvar_t sv_status_privacy;
41 static cvar_t sv_masters [] =
43 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
44 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
45 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
46 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
47 {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
48 {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
49 {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
51 {0, "sv_masterextra4", "[2001:41d0:2:1628::4450]:27950", "dpmaster.div0.qc.to - default master server 4 (admin: divVerent)"}, // admin: divVerent
56 static cvar_t sv_qwmasters [] =
58 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
59 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
60 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
61 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
62 {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
63 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
64 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
65 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
66 {0, "sv_qwmasterextra5", "qwmaster.fodquake.net:27000", "Global master server. (admin: unknown)"},
70 static double nextheartbeattime = 0;
74 static unsigned char cl_message_buf[NET_MAXMESSAGE];
75 static unsigned char sv_message_buf[NET_MAXMESSAGE];
76 char cl_readstring[MAX_INPUTLINE];
77 char sv_readstring[MAX_INPUTLINE];
79 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
80 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."};
81 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)"};
82 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
83 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
85 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)"};
86 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)"};
87 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)"};
88 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
89 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)"};
90 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
91 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"};
92 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)"};
93 static cvar_t net_slist_favorites = {CVAR_SAVE | CVAR_NQUSERINFOHACK, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
94 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
95 static cvar_t gameversion_min = {0, "gameversion_min", "-1", "minimum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
96 static cvar_t gameversion_max = {0, "gameversion_max", "-1", "maximum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
97 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode; may be set to a string of the form user1:pass1 user2:pass2 user3:pass3 to allow multiple user accounts - the client then has to specify ONE of these combinations"};
98 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
99 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)"};
100 extern cvar_t rcon_secure;
101 extern cvar_t rcon_secure_challengetimeout;
103 double masterquerytime = -1000;
104 int masterquerycount = 0;
105 int masterreplycount = 0;
106 int serverquerycount = 0;
107 int serverreplycount = 0;
109 challenge_t challenge[MAX_CHALLENGES];
111 /// this is only false if there are still servers left to query
112 static qboolean serverlist_querysleep = true;
113 static qboolean serverlist_paused = false;
114 /// this is pushed a second or two ahead of realtime whenever a master server
115 /// reply is received, to avoid issuing queries while master replies are still
116 /// flooding in (which would make a mess of the ping times)
117 static double serverlist_querywaittime = 0;
119 static int cl_numsockets;
120 static lhnetsocket_t *cl_sockets[16];
121 static int sv_numsockets;
122 static lhnetsocket_t *sv_sockets[16];
124 netconn_t *netconn_list = NULL;
125 mempool_t *netconn_mempool = NULL;
126 void *netconn_mutex = 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", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
131 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
133 char cl_net_extresponse[NET_EXTRESPONSE_MAX][1400];
134 int cl_net_extresponse_count = 0;
135 int cl_net_extresponse_last = 0;
137 char sv_net_extresponse[NET_EXTRESPONSE_MAX][1400];
138 int sv_net_extresponse_count = 0;
139 int sv_net_extresponse_last = 0;
141 // ServerList interface
142 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
143 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
145 serverlist_infofield_t serverlist_sortbyfield;
146 int serverlist_sortflags;
148 int serverlist_viewcount = 0;
149 unsigned short serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
151 int serverlist_maxcachecount = 0;
152 int serverlist_cachecount = 0;
153 serverlist_entry_t *serverlist_cache = NULL;
155 qboolean serverlist_consoleoutput;
157 static int nFavorites = 0;
158 static lhnetaddress_t favorites[MAX_FAVORITESERVERS];
159 static int nFavorites_idfp = 0;
160 static char favorites_idfp[MAX_FAVORITESERVERS][FP64_SIZE+1];
162 void NetConn_UpdateFavorites(void)
167 p = net_slist_favorites.string;
168 while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
170 if(com_token[0] != '[' && strlen(com_token) == FP64_SIZE && !strchr(com_token, '.'))
171 // currently 44 bytes, longest possible IPv6 address: 39 bytes, so this works
172 // (if v6 address contains port, it must start with '[')
174 strlcpy(favorites_idfp[nFavorites_idfp], com_token, sizeof(favorites_idfp[nFavorites_idfp]));
179 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
185 /// helper function to insert a value into the viewset
186 /// spare entries will be removed
187 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
190 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
191 i = serverlist_viewcount++;
193 i = SERVERLIST_VIEWLISTSIZE - 1;
196 for( ; i > index ; i-- )
197 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
199 serverlist_viewlist[index] = (int)(entry - serverlist_cache);
202 /// we suppose serverlist_viewcount to be valid, ie > 0
203 static void _ServerList_ViewList_Helper_Remove( int index )
205 serverlist_viewcount--;
206 for( ; index < serverlist_viewcount ; index++ )
207 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
210 /// \returns true if A should be inserted before B
211 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
213 int result = 0; // > 0 if for numbers A > B and for text if A < B
215 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
217 if(A->info.isfavorite != B->info.isfavorite)
218 return A->info.isfavorite;
221 switch( serverlist_sortbyfield ) {
223 result = A->info.ping - B->info.ping;
225 case SLIF_MAXPLAYERS:
226 result = A->info.maxplayers - B->info.maxplayers;
228 case SLIF_NUMPLAYERS:
229 result = A->info.numplayers - B->info.numplayers;
232 result = A->info.numbots - B->info.numbots;
235 result = A->info.numhumans - B->info.numhumans;
238 result = A->info.freeslots - B->info.freeslots;
241 result = A->info.protocol - B->info.protocol;
244 result = strcmp( B->info.cname, A->info.cname );
247 result = strcasecmp( B->info.game, A->info.game );
250 result = strcasecmp( B->info.map, A->info.map );
253 result = strcasecmp( B->info.mod, A->info.mod );
256 result = strcasecmp( B->info.name, A->info.name );
259 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
261 case SLIF_ISFAVORITE:
262 result = !!B->info.isfavorite - !!A->info.isfavorite;
265 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
271 if( serverlist_sortflags & SLSF_DESCENDING )
277 // if the chosen sort key is identical, sort by index
278 // (makes this a stable sort, so that later replies from servers won't
279 // shuffle the servers around when they have the same ping)
283 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
285 // This should actually be done with some intermediate and end-of-function return
297 case SLMO_GREATEREQUAL:
299 case SLMO_NOTCONTAIN:
300 case SLMO_STARTSWITH:
301 case SLMO_NOTSTARTSWITH:
304 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
309 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
312 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
313 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
314 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
315 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
317 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
318 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
321 // Same here, also using an intermediate & final return would be more appropriate
325 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
326 case SLMO_NOTCONTAIN:
327 return !*bufferB || !strstr( bufferA, bufferB );
328 case SLMO_STARTSWITH:
329 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
330 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
331 case SLMO_NOTSTARTSWITH:
332 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
334 return strcmp( bufferA, bufferB ) < 0;
336 return strcmp( bufferA, bufferB ) <= 0;
338 return strcmp( bufferA, bufferB ) == 0;
340 return strcmp( bufferA, bufferB ) > 0;
342 return strcmp( bufferA, bufferB ) != 0;
343 case SLMO_GREATEREQUAL:
344 return strcmp( bufferA, bufferB ) >= 0;
346 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
351 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
353 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
355 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
357 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
359 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
361 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
363 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
365 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
367 if( *mask->info.cname
368 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
371 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
374 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
377 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
380 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
382 if( *mask->info.qcstatus
383 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
385 if( *mask->info.players
386 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
388 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
393 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
395 int start, end, mid, i;
398 // reject incompatible servers
400 entry->info.gameversion != gameversion.integer
403 gameversion_min.integer >= 0 // min/max range set by user/mod?
404 && gameversion_max.integer >= 0
405 && gameversion_min.integer <= entry->info.gameversion // version of server in min/max range?
406 && gameversion_max.integer >= entry->info.gameversion
411 // refresh the "favorite" status
412 entry->info.isfavorite = false;
413 if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
415 char idfp[FP64_SIZE+1];
416 for(i = 0; i < nFavorites; ++i)
418 if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
420 entry->info.isfavorite = true;
424 if(Crypto_RetrieveHostKey(&addr, 0, NULL, 0, idfp, sizeof(idfp), NULL))
426 for(i = 0; i < nFavorites_idfp; ++i)
428 if(!strcmp(idfp, favorites_idfp[i]))
430 entry->info.isfavorite = true;
437 // FIXME: change this to be more readable (...)
438 // now check whether it passes through the masks
439 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
440 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
443 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
444 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
446 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
449 if( !serverlist_viewcount ) {
450 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
453 // ok, insert it, we just need to find out where exactly:
456 // check whether to insert it as new first item
457 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(0) ) ) {
458 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
460 } // check whether to insert it as new last item
461 else if( !_ServerList_Entry_Compare( entry, ServerList_GetViewEntry(serverlist_viewcount - 1) ) ) {
462 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
466 end = serverlist_viewcount - 1;
467 while( end > start + 1 )
469 mid = (start + end) / 2;
470 // test the item that lies in the middle between start and end
471 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(mid) ) )
472 // the item has to be in the upper half
475 // the item has to be in the lower half
478 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
481 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
484 for( i = 0; i < serverlist_viewcount; i++ )
486 if (ServerList_GetViewEntry(i) == entry)
488 _ServerList_ViewList_Helper_Remove(i);
494 void ServerList_RebuildViewList(void)
498 serverlist_viewcount = 0;
499 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
500 serverlist_entry_t *entry = &serverlist_cache[i];
501 // also display entries that are currently being refreshed [11/8/2007 Black]
502 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
503 ServerList_ViewList_Insert( entry );
507 void ServerList_ResetMasks(void)
511 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
512 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
513 // numbots needs to be compared to -1 to always succeed
514 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
515 serverlist_andmasks[i].info.numbots = -1;
516 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
517 serverlist_ormasks[i].info.numbots = -1;
520 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
523 int numplayers = 0, maxplayers = 0;
524 for (i = 0;i < serverlist_cachecount;i++)
526 if (serverlist_cache[i].query == SQS_QUERIED)
528 numplayers += serverlist_cache[i].info.numhumans;
529 maxplayers += serverlist_cache[i].info.maxplayers;
532 *numplayerspointer = numplayers;
533 *maxplayerspointer = maxplayers;
537 static void _ServerList_Test(void)
540 if (serverlist_maxcachecount <= 1024)
542 serverlist_maxcachecount = 1024;
543 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
545 for( i = 0 ; i < 1024 ; i++ ) {
546 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
547 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
548 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
549 serverlist_cache[serverlist_cachecount].finished = true;
550 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 );
551 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
552 serverlist_cachecount++;
557 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
559 masterquerytime = realtime;
560 masterquerycount = 0;
561 masterreplycount = 0;
563 serverquerycount = 0;
564 serverreplycount = 0;
565 serverlist_cachecount = 0;
566 serverlist_viewcount = 0;
567 serverlist_maxcachecount = 0;
568 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
570 // refresh all entries
572 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
573 serverlist_entry_t *entry = &serverlist_cache[ n ];
574 entry->query = SQS_REFRESHING;
575 entry->querycounter = 0;
578 serverlist_consoleoutput = consoleoutput;
580 //_ServerList_Test();
582 NetConn_QueryMasters(querydp, queryqw);
587 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
591 if (mysocket->address.addresstype == LHNETADDRESSTYPE_LOOP && netconn_mutex)
592 Thread_LockMutex(netconn_mutex);
593 length = LHNET_Read(mysocket, data, maxlength, peeraddress);
594 if (mysocket->address.addresstype == LHNETADDRESSTYPE_LOOP && netconn_mutex)
595 Thread_UnlockMutex(netconn_mutex);
598 if (cl_netpacketloss_receive.integer)
599 for (i = 0;i < cl_numsockets;i++)
600 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
602 if (developer_networking.integer)
604 char addressstring[128], addressstring2[128];
605 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
608 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
609 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
610 Com_HexDumpToConsole((unsigned char *)data, length);
613 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
618 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
622 if (cl_netpacketloss_send.integer)
623 for (i = 0;i < cl_numsockets;i++)
624 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
626 if (mysocket->address.addresstype == LHNETADDRESSTYPE_LOOP && netconn_mutex)
627 Thread_LockMutex(netconn_mutex);
628 ret = LHNET_Write(mysocket, data, length, peeraddress);
629 if (mysocket->address.addresstype == LHNETADDRESSTYPE_LOOP && netconn_mutex)
630 Thread_UnlockMutex(netconn_mutex);
631 if (developer_networking.integer)
633 char addressstring[128], addressstring2[128];
634 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
635 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
636 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", (void *)mysocket, addressstring, (void *)data, length, (void *)peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
637 Com_HexDumpToConsole((unsigned char *)data, length);
642 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
644 // note this does not include the trailing NULL because we add that in the parser
645 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
648 qboolean NetConn_CanSend(netconn_t *conn)
650 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
651 conn->outgoing_netgraph[conn->outgoing_packetcounter].time = realtime;
652 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
653 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
654 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes = NETGRAPH_NOPACKET;
655 if (realtime > conn->cleartime)
659 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_CHOKEDPACKET;
664 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
667 unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
668 unsigned char cryptosendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
670 // if this packet was supposedly choked, but we find ourselves sending one
671 // anyway, make sure the size counting starts at zero
672 // (this mostly happens on level changes and disconnects and such)
673 if (conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes == NETGRAPH_CHOKEDPACKET)
674 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
676 if (protocol == PROTOCOL_QUAKEWORLD)
679 qboolean sendreliable;
681 // note that it is ok to send empty messages to the qw server,
682 // otherwise it won't respond to us at all
684 sendreliable = false;
685 // if the remote side dropped the last reliable message, resend it
686 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
688 // if the reliable transmit buffer is empty, copy the current message out
689 if (!conn->sendMessageLength && conn->message.cursize)
691 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
692 conn->sendMessageLength = conn->message.cursize;
693 SZ_Clear(&conn->message); // clear the message buffer
694 conn->qw.reliable_sequence ^= 1;
697 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
698 StoreLittleLong(sendbuffer, (unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
699 // last received unreliable packet number, and last received reliable packet number (0 or 1)
700 StoreLittleLong(sendbuffer + 4, (unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
702 conn->outgoing_unreliable_sequence++;
703 // client sends qport in every packet
704 if (conn == cls.netcon)
706 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
708 // also update cls.qw_outgoing_sequence
709 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
711 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
713 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
717 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
719 // add the reliable message if there is one
722 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += conn->sendMessageLength + 28;
723 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
724 packetLen += conn->sendMessageLength;
725 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
728 // add the unreliable message if possible
729 if (packetLen + data->cursize <= 1400)
731 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += data->cursize + 28;
732 memcpy(sendbuffer + packetLen, data->data, data->cursize);
733 packetLen += data->cursize;
736 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
739 conn->unreliableMessagesSent++;
741 totallen += packetLen + 28;
745 unsigned int packetLen;
746 unsigned int dataLen;
751 // if a reliable message fragment has been lost, send it again
752 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
754 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
756 dataLen = conn->sendMessageLength;
761 dataLen = MAX_PACKETFRAGMENT;
765 packetLen = NET_HEADERSIZE + dataLen;
767 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
768 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence - 1);
769 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
771 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
773 sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
774 if (sendme && NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress) == (int)sendmelen)
776 conn->lastSendTime = realtime;
777 conn->packetsReSent++;
780 totallen += sendmelen + 28;
783 // if we have a new reliable message to send, do so
784 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
786 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
788 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
789 conn->message.overflowed = true;
793 if (developer_networking.integer && conn == cls.netcon)
795 Con_Print("client sending reliable message to server:\n");
796 SZ_HexDumpToConsole(&conn->message);
799 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
800 conn->sendMessageLength = conn->message.cursize;
801 SZ_Clear(&conn->message);
803 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
805 dataLen = conn->sendMessageLength;
810 dataLen = MAX_PACKETFRAGMENT;
814 packetLen = NET_HEADERSIZE + dataLen;
816 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
817 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
818 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
820 conn->nq.sendSequence++;
822 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
824 sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
826 NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
828 conn->lastSendTime = realtime;
830 conn->reliableMessagesSent++;
832 totallen += sendmelen + 28;
835 // if we have an unreliable message to send, do so
838 packetLen = NET_HEADERSIZE + data->cursize;
840 if (packetLen > (int)sizeof(sendbuffer))
842 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
846 StoreBigLong(sendbuffer, packetLen | NETFLAG_UNRELIABLE);
847 StoreBigLong(sendbuffer + 4, conn->outgoing_unreliable_sequence);
848 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
850 conn->outgoing_unreliable_sequence++;
852 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
854 sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
856 NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
859 conn->unreliableMessagesSent++;
861 totallen += sendmelen + 28;
865 // delay later packets to obey rate limit
866 if (conn->cleartime < realtime - 0.1)
867 conn->cleartime = realtime - 0.1;
868 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
869 if (conn->cleartime < realtime)
870 conn->cleartime = realtime;
875 qboolean NetConn_HaveClientPorts(void)
877 return !!cl_numsockets;
880 qboolean NetConn_HaveServerPorts(void)
882 return !!sv_numsockets;
885 void NetConn_CloseClientPorts(void)
887 for (;cl_numsockets > 0;cl_numsockets--)
888 if (cl_sockets[cl_numsockets - 1])
889 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
892 static void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
894 lhnetaddress_t address;
897 char addressstring2[1024];
898 if (addressstring && addressstring[0])
899 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
901 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
904 if ((s = LHNET_OpenSocket_Connectionless(&address)))
906 cl_sockets[cl_numsockets++] = s;
907 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
908 if (addresstype != LHNETADDRESSTYPE_LOOP)
909 Con_Printf("Client opened a socket on address %s\n", addressstring2);
913 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
914 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
918 Con_Printf("Client unable to parse address %s\n", addressstring);
921 void NetConn_OpenClientPorts(void)
924 NetConn_CloseClientPorts();
926 SV_LockThreadMutex(); // FIXME recursive?
927 Crypto_LoadKeys(); // client sockets
928 SV_UnlockThreadMutex();
930 port = bound(0, cl_netport.integer, 65535);
931 if (cl_netport.integer != port)
932 Cvar_SetValueQuick(&cl_netport, port);
934 Con_Printf("Client using an automatically assigned port\n");
936 Con_Printf("Client using port %i\n", port);
937 NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
938 NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
940 NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
944 void NetConn_CloseServerPorts(void)
946 for (;sv_numsockets > 0;sv_numsockets--)
947 if (sv_sockets[sv_numsockets - 1])
948 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
951 static qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
953 lhnetaddress_t address;
956 char addressstring2[1024];
959 for (port = defaultport; port <= defaultport + range; port++)
961 if (addressstring && addressstring[0])
962 success = LHNETADDRESS_FromString(&address, addressstring, port);
964 success = LHNETADDRESS_FromPort(&address, addresstype, port);
967 if ((s = LHNET_OpenSocket_Connectionless(&address)))
969 sv_sockets[sv_numsockets++] = s;
970 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
971 if (addresstype != LHNETADDRESSTYPE_LOOP)
972 Con_Printf("Server listening on address %s\n", addressstring2);
977 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
978 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
983 Con_Printf("Server unable to parse address %s\n", addressstring);
984 // if it cant parse one address, it wont be able to parse another for sure
991 void NetConn_OpenServerPorts(int opennetports)
994 NetConn_CloseServerPorts();
996 SV_LockThreadMutex(); // FIXME recursive?
997 Crypto_LoadKeys(); // server sockets
998 SV_UnlockThreadMutex();
1000 NetConn_UpdateSockets();
1001 port = bound(0, sv_netport.integer, 65535);
1004 Con_Printf("Server using port %i\n", port);
1005 if (sv_netport.integer != port)
1006 Cvar_SetValueQuick(&sv_netport, port);
1007 if (cls.state != ca_dedicated)
1008 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
1012 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1013 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
1015 NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1018 if (sv_numsockets == 0)
1019 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
1022 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
1024 int i, a = LHNETADDRESS_GetAddressType(address);
1025 for (i = 0;i < cl_numsockets;i++)
1026 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
1027 return cl_sockets[i];
1031 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
1033 int i, a = LHNETADDRESS_GetAddressType(address);
1034 for (i = 0;i < sv_numsockets;i++)
1035 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
1036 return sv_sockets[i];
1040 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
1043 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
1044 conn->mysocket = mysocket;
1045 conn->peeraddress = *peeraddress;
1046 conn->lastMessageTime = realtime;
1047 conn->message.data = conn->messagedata;
1048 conn->message.maxsize = sizeof(conn->messagedata);
1049 conn->message.cursize = 0;
1050 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
1051 // reduce effectiveness of connection request floods
1052 conn->timeout = realtime + net_connecttimeout.value;
1053 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
1054 conn->next = netconn_list;
1055 netconn_list = conn;
1059 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
1060 void NetConn_Close(netconn_t *conn)
1063 // remove connection from list
1065 // allow the client to reconnect immediately
1066 NetConn_ClearConnectFlood(&(conn->peeraddress));
1068 if (conn == netconn_list)
1069 netconn_list = conn->next;
1072 for (c = netconn_list;c;c = c->next)
1074 if (c->next == conn)
1076 c->next = conn->next;
1080 // not found in list, we'll avoid crashing here...
1088 static int clientport = -1;
1089 static int clientport2 = -1;
1090 static int hostport = -1;
1091 void NetConn_UpdateSockets(void)
1095 if (cls.state != ca_dedicated)
1097 if (clientport2 != cl_netport.integer)
1099 clientport2 = cl_netport.integer;
1100 if (cls.state == ca_connected)
1101 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1103 if (cls.state == ca_disconnected && clientport != clientport2)
1105 clientport = clientport2;
1106 NetConn_CloseClientPorts();
1108 if (cl_numsockets == 0)
1109 NetConn_OpenClientPorts();
1112 if (hostport != sv_netport.integer)
1114 hostport = sv_netport.integer;
1116 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1119 for (j = 0;j < MAX_RCONS;j++)
1121 i = (cls.rcon_ringpos + j + 1) % MAX_RCONS;
1122 if(cls.rcon_commands[i][0])
1124 if(realtime > cls.rcon_timeout[i])
1127 LHNETADDRESS_ToString(&cls.rcon_addresses[i], s, sizeof(s), true);
1128 Con_Printf("rcon to %s (for command %s) failed: challenge request timed out\n", s, cls.rcon_commands[i]);
1129 cls.rcon_commands[i][0] = 0;
1137 static int NetConn_ReceivedMessage(netconn_t *conn, const unsigned char *data, size_t length, protocolversion_t protocol, double newtimeout)
1139 int originallength = length;
1140 unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
1141 unsigned char cryptosendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1142 unsigned char cryptoreadbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1146 if (protocol == PROTOCOL_QUAKEWORLD)
1148 int sequence, sequence_ack;
1149 int reliable_ack, reliable_message;
1153 sequence = LittleLong(*((int *)(data + 0)));
1154 sequence_ack = LittleLong(*((int *)(data + 4)));
1158 if (conn != cls.netcon)
1163 // 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?)
1164 //qport = LittleShort(*((int *)(data + 8)));
1169 conn->packetsReceived++;
1170 reliable_message = (sequence >> 31) & 1;
1171 reliable_ack = (sequence_ack >> 31) & 1;
1172 sequence &= ~(1<<31);
1173 sequence_ack &= ~(1<<31);
1174 if (sequence <= conn->qw.incoming_sequence)
1176 //Con_DPrint("Got a stale datagram\n");
1179 count = sequence - (conn->qw.incoming_sequence + 1);
1182 conn->droppedDatagrams += count;
1183 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1186 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1187 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1188 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1189 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1190 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1193 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1194 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1195 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1196 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1197 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1198 if (reliable_ack == conn->qw.reliable_sequence)
1200 // received, now we will be able to send another reliable message
1201 conn->sendMessageLength = 0;
1202 conn->reliableMessagesReceived++;
1204 conn->qw.incoming_sequence = sequence;
1205 if (conn == cls.netcon)
1206 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1207 conn->qw.incoming_acknowledged = sequence_ack;
1208 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1209 if (reliable_message)
1210 conn->qw.incoming_reliable_sequence ^= 1;
1211 conn->lastMessageTime = realtime;
1212 conn->timeout = realtime + newtimeout;
1213 conn->unreliableMessagesReceived++;
1214 if (conn == cls.netcon)
1216 SZ_Clear(&cl_message);
1217 SZ_Write(&cl_message, data, length);
1218 MSG_BeginReading(&cl_message);
1222 SZ_Clear(&sv_message);
1223 SZ_Write(&sv_message, data, length);
1224 MSG_BeginReading(&sv_message);
1232 unsigned int sequence;
1237 originallength = length;
1238 data = (const unsigned char *) Crypto_DecryptPacket(&conn->crypto, data, length, cryptoreadbuffer, &length, sizeof(cryptoreadbuffer));
1244 qlength = (unsigned int)BuffBigLong(data);
1245 flags = qlength & ~NETFLAG_LENGTH_MASK;
1246 qlength &= NETFLAG_LENGTH_MASK;
1247 // control packets were already handled
1248 if (!(flags & NETFLAG_CTL) && qlength == length)
1250 sequence = BuffBigLong(data + 4);
1251 conn->packetsReceived++;
1254 if (flags & NETFLAG_UNRELIABLE)
1256 if (sequence >= conn->nq.unreliableReceiveSequence)
1258 if (sequence > conn->nq.unreliableReceiveSequence)
1260 count = sequence - conn->nq.unreliableReceiveSequence;
1261 conn->droppedDatagrams += count;
1262 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1265 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1266 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1267 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1268 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1269 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1272 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1273 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1274 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1275 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1276 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1277 conn->nq.unreliableReceiveSequence = sequence + 1;
1278 conn->lastMessageTime = realtime;
1279 conn->timeout = realtime + newtimeout;
1280 conn->unreliableMessagesReceived++;
1283 if (conn == cls.netcon)
1285 SZ_Clear(&cl_message);
1286 SZ_Write(&cl_message, data, length);
1287 MSG_BeginReading(&cl_message);
1291 SZ_Clear(&sv_message);
1292 SZ_Write(&sv_message, data, length);
1293 MSG_BeginReading(&sv_message);
1299 // Con_DPrint("Got a stale datagram\n");
1302 else if (flags & NETFLAG_ACK)
1304 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1305 if (sequence == (conn->nq.sendSequence - 1))
1307 if (sequence == conn->nq.ackSequence)
1309 conn->nq.ackSequence++;
1310 if (conn->nq.ackSequence != conn->nq.sendSequence)
1311 Con_DPrint("ack sequencing error\n");
1312 conn->lastMessageTime = realtime;
1313 conn->timeout = realtime + newtimeout;
1314 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1316 unsigned int packetLen;
1317 unsigned int dataLen;
1320 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1321 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1323 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1325 dataLen = conn->sendMessageLength;
1330 dataLen = MAX_PACKETFRAGMENT;
1334 packetLen = NET_HEADERSIZE + dataLen;
1336 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
1337 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
1338 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1340 conn->nq.sendSequence++;
1342 sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1343 if (sendme && NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress) == (int)sendmelen)
1345 conn->lastSendTime = realtime;
1346 conn->packetsSent++;
1350 conn->sendMessageLength = 0;
1353 // Con_DPrint("Duplicate ACK received\n");
1356 // Con_DPrint("Stale ACK received\n");
1359 else if (flags & NETFLAG_DATA)
1361 unsigned char temppacket[8];
1362 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes += originallength + 28;
1363 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes += 8 + 28;
1364 StoreBigLong(temppacket, 8 | NETFLAG_ACK);
1365 StoreBigLong(temppacket + 4, sequence);
1366 sendme = Crypto_EncryptPacket(&conn->crypto, temppacket, 8, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1368 NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
1369 if (sequence == conn->nq.receiveSequence)
1371 conn->lastMessageTime = realtime;
1372 conn->timeout = realtime + newtimeout;
1373 conn->nq.receiveSequence++;
1374 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1375 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1376 conn->receiveMessageLength += length;
1378 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1379 "Dropping the message!\n", sequence );
1380 conn->receiveMessageLength = 0;
1383 if (flags & NETFLAG_EOM)
1385 conn->reliableMessagesReceived++;
1386 length = conn->receiveMessageLength;
1387 conn->receiveMessageLength = 0;
1390 if (conn == cls.netcon)
1392 SZ_Clear(&cl_message);
1393 SZ_Write(&cl_message, conn->receiveMessage, length);
1394 MSG_BeginReading(&cl_message);
1398 SZ_Clear(&sv_message);
1399 SZ_Write(&sv_message, conn->receiveMessage, length);
1400 MSG_BeginReading(&sv_message);
1407 conn->receivedDuplicateCount++;
1415 static void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1418 cls.connect_trying = false;
1419 M_Update_Return_Reason("");
1420 // the connection request succeeded, stop current connection and set up a new connection
1422 // if we're connecting to a remote server, shut down any local server
1423 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1425 SV_LockThreadMutex();
1426 Host_ShutdownServer ();
1427 SV_UnlockThreadMutex();
1429 // allocate a net connection to keep track of things
1430 cls.netcon = NetConn_Open(mysocket, peeraddress);
1431 crypto = &cls.crypto;
1432 if(crypto && crypto->authenticated)
1434 Crypto_ServerFinishInstance(&cls.netcon->crypto, crypto);
1435 Con_Printf("%s connection to %s has been established: server is %s@%.*s, I am %.*s@%.*s\n",
1436 crypto->use_aes ? "Encrypted" : "Authenticated",
1437 cls.netcon->address,
1438 crypto->server_idfp[0] ? crypto->server_idfp : "-",
1439 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-",
1440 crypto_keyfp_recommended_length, crypto->client_idfp[0] ? crypto->client_idfp : "-",
1441 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-"
1444 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1445 key_dest = key_game;
1447 cls.demonum = -1; // not in the demo loop now
1448 cls.state = ca_connected;
1449 cls.signon = 0; // need all the signon messages before playing
1450 cls.protocol = initialprotocol;
1451 // reset move sequence numbering on this new connection
1452 cls.servermovesequence = 0;
1453 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1454 Cmd_ForwardStringToServer("new");
1455 if (cls.protocol == PROTOCOL_QUAKE)
1457 // write a keepalive (clc_nop) as it seems to greatly improve the
1458 // chances of connecting to a netquake server
1460 unsigned char buf[4];
1461 memset(&msg, 0, sizeof(msg));
1463 msg.maxsize = sizeof(buf);
1464 MSG_WriteChar(&msg, clc_nop);
1465 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1469 int NetConn_IsLocalGame(void)
1471 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1476 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1480 serverlist_entry_t *entry = NULL;
1482 // search the cache for this server and update it
1483 for (n = 0;n < serverlist_cachecount;n++) {
1484 entry = &serverlist_cache[ n ];
1485 if (!strcmp(addressstring, entry->info.cname))
1489 if (n == serverlist_cachecount)
1491 // LAN search doesnt require an answer from the master server so we wont
1492 // know the ping nor will it be initialized already...
1495 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1498 if (serverlist_maxcachecount <= serverlist_cachecount)
1500 serverlist_maxcachecount += 64;
1501 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1503 entry = &serverlist_cache[n];
1505 memset(entry, 0, sizeof(*entry));
1506 // store the data the engine cares about (address and ping)
1507 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1508 entry->info.ping = 100000;
1509 entry->querytime = realtime;
1510 // if not in the slist menu we should print the server to console
1511 if (serverlist_consoleoutput)
1512 Con_Printf("querying %s\n", addressstring);
1513 ++serverlist_cachecount;
1515 // if this is the first reply from this server, count it as having replied
1516 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1517 pingtime = bound(0, pingtime, 9999);
1518 if (entry->query == SQS_REFRESHING) {
1519 entry->info.ping = pingtime;
1520 entry->query = SQS_QUERIED;
1522 // convert to unsigned to catch the -1
1523 // 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]
1524 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1528 // other server info is updated by the caller
1532 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1534 serverlist_entry_t *entry = &serverlist_cache[n];
1535 serverlist_info_t *info = &entry->info;
1536 // update description strings for engine menu and console output
1537 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);
1538 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1540 info->gameversion != gameversion.integer
1543 gameversion_min.integer >= 0 // min/max range set by user/mod?
1544 && gameversion_max.integer >= 0
1545 && gameversion_min.integer <= info->gameversion // version of server in min/max range?
1546 && gameversion_max.integer >= info->gameversion
1549 info->mod, info->map);
1550 if (entry->query == SQS_QUERIED)
1552 if(!serverlist_paused)
1553 ServerList_ViewList_Remove(entry);
1555 // if not in the slist menu we should print the server to console (if wanted)
1556 else if( serverlist_consoleoutput )
1557 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1558 // and finally, update the view set
1559 if(!serverlist_paused)
1560 ServerList_ViewList_Insert( entry );
1561 // update the entry's state
1562 serverlist_cache[n].query = SQS_QUERIED;
1565 // returns true, if it's sensible to continue the processing
1566 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1568 serverlist_entry_t *entry;
1570 // ignore the rest of the message if the serverlist is full
1571 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1573 // also ignore it if we have already queried it (other master server response)
1574 for( n = 0 ; n < serverlist_cachecount ; n++ )
1575 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1578 if( n < serverlist_cachecount ) {
1579 // the entry has already been queried once or
1583 if (serverlist_maxcachecount <= n)
1585 serverlist_maxcachecount += 64;
1586 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1589 entry = &serverlist_cache[n];
1591 memset(entry, 0, sizeof(*entry));
1592 entry->protocol = protocol;
1593 // store the data the engine cares about (address and ping)
1594 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1596 entry->info.isfavorite = isfavorite;
1598 // no, then reset the ping right away
1599 entry->info.ping = -1;
1600 // we also want to increase the serverlist_cachecount then
1601 serverlist_cachecount++;
1604 entry->query = SQS_QUERYING;
1609 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1612 if (serverlist_consoleoutput)
1613 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1616 char ipstring [128];
1619 if (data[0] == '\\')
1621 unsigned short port = data[5] * 256 + data[6];
1623 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1624 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1626 // move on to next address in packet
1631 else if (data[0] == '/' && isextended && length >= 19)
1633 unsigned short port = data[17] * 256 + data[18];
1641 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1643 ifname = LHNETADDRESS_GetInterfaceName(senderaddress, ifnamebuf, sizeof(ifnamebuf));
1646 dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x%%%s]:%hu",
1647 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1648 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1654 dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x]:%hu",
1655 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1656 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1661 // move on to next address in packet
1667 Con_Print("Error while parsing the server list\n");
1671 if (serverlist_consoleoutput && developer_networking.integer)
1672 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1674 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1680 // begin or resume serverlist queries
1681 serverlist_querysleep = false;
1682 serverlist_querywaittime = realtime + 3;
1685 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1687 qboolean fromserver;
1690 char *string, addressstring2[128], ipstring[32];
1691 char stringbuf[16384];
1692 char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1694 char infostringvalue[MAX_INPUTLINE];
1697 // quakeworld ingame packet
1698 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1700 // convert the address to a string incase we need it
1701 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1703 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1705 // received a command string - strip off the packaging and put it
1706 // into our string buffer with NULL termination
1709 length = min(length, (int)sizeof(stringbuf) - 1);
1710 memcpy(stringbuf, data, length);
1711 stringbuf[length] = 0;
1714 if (developer_networking.integer)
1716 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1717 Com_HexDumpToConsole(data, length);
1720 sendlength = sizeof(senddata) - 4;
1721 switch(Crypto_ClientParsePacket(string, length, senddata+4, &sendlength, peeraddress))
1723 case CRYPTO_NOMATCH:
1729 memcpy(senddata, "\377\377\377\377", 4);
1730 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1733 case CRYPTO_DISCARD:
1736 memcpy(senddata, "\377\377\377\377", 4);
1737 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1741 case CRYPTO_REPLACE:
1742 string = senddata+4;
1743 length = sendlength;
1747 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1750 for (j = 0;j < MAX_RCONS;j++)
1752 // note: this value from i is used outside the loop too...
1753 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1754 if(cls.rcon_commands[i][0])
1755 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1764 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1765 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1767 e = strchr(rcon_password.string, ' ');
1768 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1770 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1774 strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1775 NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1776 cls.rcon_commands[i][0] = 0;
1779 for (k = 0;k < MAX_RCONS;k++)
1780 if(cls.rcon_commands[k][0])
1781 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1786 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1787 // extend the timeout on other requests as we asked for a challenge
1788 for (l = 0;l < MAX_RCONS;l++)
1789 if(cls.rcon_commands[l][0])
1790 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1791 cls.rcon_timeout[l] = realtime + rcon_secure_challengetimeout.value;
1794 return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1798 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1800 // darkplaces or quake3
1801 char protocolnames[1400];
1802 Protocol_Names(protocolnames, sizeof(protocolnames));
1803 Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1804 M_Update_Return_Reason("Got challenge response");
1805 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1806 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1807 // TODO: add userinfo stuff here instead of using NQ commands?
1808 NetConn_WriteString(mysocket, va(vabuf, sizeof(vabuf), "\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s%s\\challenge\\%s", protocolnames, cls.connect_userinfo, string + 10), peeraddress);
1811 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1813 // darkplaces or quake3
1814 M_Update_Return_Reason("Accepted");
1815 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1818 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1820 char rejectreason[128];
1821 cls.connect_trying = false;
1823 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1824 memcpy(rejectreason, string, length);
1825 rejectreason[length] = 0;
1826 M_Update_Return_Reason(rejectreason);
1829 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1831 serverlist_info_t *info;
1836 // search the cache for this server and update it
1837 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1841 info = &serverlist_cache[n].info;
1846 info->qcstatus[0] = 0;
1847 info->players[0] = 0;
1848 info->protocol = -1;
1849 info->numplayers = 0;
1851 info->maxplayers = 0;
1852 info->gameversion = 0;
1854 p = strchr(string, '\n');
1857 *p = 0; // cut off the string there
1861 Con_Printf("statusResponse without players block?\n");
1863 if ((s = InfoString_GetValue(string, "gamename" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->game, s, sizeof (info->game));
1864 if ((s = InfoString_GetValue(string, "modname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1865 if ((s = InfoString_GetValue(string, "mapname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1866 if ((s = InfoString_GetValue(string, "hostname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));
1867 if ((s = InfoString_GetValue(string, "protocol" , infostringvalue, sizeof(infostringvalue))) != NULL) info->protocol = atoi(s);
1868 if ((s = InfoString_GetValue(string, "clients" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numplayers = atoi(s);
1869 if ((s = InfoString_GetValue(string, "bots" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numbots = atoi(s);
1870 if ((s = InfoString_GetValue(string, "sv_maxclients", infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);
1871 if ((s = InfoString_GetValue(string, "gameversion" , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);
1872 if ((s = InfoString_GetValue(string, "qcstatus" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1873 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1874 info->numhumans = info->numplayers - max(0, info->numbots);
1875 info->freeslots = info->maxplayers - info->numplayers;
1877 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1881 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1883 serverlist_info_t *info;
1887 // search the cache for this server and update it
1888 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1892 info = &serverlist_cache[n].info;
1897 info->qcstatus[0] = 0;
1898 info->players[0] = 0;
1899 info->protocol = -1;
1900 info->numplayers = 0;
1902 info->maxplayers = 0;
1903 info->gameversion = 0;
1905 if ((s = InfoString_GetValue(string, "gamename" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->game, s, sizeof (info->game));
1906 if ((s = InfoString_GetValue(string, "modname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1907 if ((s = InfoString_GetValue(string, "mapname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1908 if ((s = InfoString_GetValue(string, "hostname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));
1909 if ((s = InfoString_GetValue(string, "protocol" , infostringvalue, sizeof(infostringvalue))) != NULL) info->protocol = atoi(s);
1910 if ((s = InfoString_GetValue(string, "clients" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numplayers = atoi(s);
1911 if ((s = InfoString_GetValue(string, "bots" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numbots = atoi(s);
1912 if ((s = InfoString_GetValue(string, "sv_maxclients", infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);
1913 if ((s = InfoString_GetValue(string, "gameversion" , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);
1914 if ((s = InfoString_GetValue(string, "qcstatus" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1915 info->numhumans = info->numplayers - max(0, info->numbots);
1916 info->freeslots = info->maxplayers - info->numplayers;
1918 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1922 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1924 // Extract the IP addresses
1927 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1930 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1932 // Extract the IP addresses
1935 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1938 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1940 // Extract the IP addresses
1944 if (serverlist_consoleoutput)
1945 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1946 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1948 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1949 if (serverlist_consoleoutput && developer_networking.integer)
1950 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1952 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1956 // move on to next address in packet
1960 // begin or resume serverlist queries
1961 serverlist_querysleep = false;
1962 serverlist_querywaittime = realtime + 3;
1965 if (!strncmp(string, "extResponse ", 12))
1967 ++cl_net_extresponse_count;
1968 if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1969 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1970 cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1971 dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1974 if (!strncmp(string, "ping", 4))
1976 if (developer_extra.integer)
1977 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1978 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1981 if (!strncmp(string, "ack", 3))
1983 // QuakeWorld compatibility
1984 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1986 // challenge message
1987 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1988 M_Update_Return_Reason("Got QuakeWorld challenge response");
1989 cls.qw_qport = qport.integer;
1990 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1991 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1992 NetConn_WriteString(mysocket, va(vabuf, sizeof(vabuf), "\377\377\377\377connect %i %i %i \"%s%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo, cls.connect_userinfo), peeraddress);
1995 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1998 M_Update_Return_Reason("QuakeWorld Accepted");
1999 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
2002 if (length > 2 && !memcmp(string, "n\\", 2))
2004 serverlist_info_t *info;
2008 if (serverlist_consoleoutput && developer_networking.integer >= 2)
2009 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
2012 // search the cache for this server and update it
2013 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2017 info = &serverlist_cache[n].info;
2018 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
2019 if ((s = InfoString_GetValue(string, "*gamedir" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
2020 if ((s = InfoString_GetValue(string, "map" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
2021 if ((s = InfoString_GetValue(string, "hostname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
2023 info->numplayers = 0; // updated below
2024 info->numhumans = 0; // updated below
2025 if ((s = InfoString_GetValue(string, "maxclients" , infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
2026 if ((s = InfoString_GetValue(string, "gameversion" , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
2028 // count active players on server
2029 // (we could gather more info, but we're just after the number)
2030 s = strchr(string, '\n');
2034 while (s < string + length)
2036 for (;s < string + length && *s != '\n';s++)
2038 if (s >= string + length)
2046 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2050 if (string[0] == 'n')
2053 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
2055 // we may not have liked the packet, but it was a command packet, so
2056 // we're done processing this packet now
2059 // quakeworld ingame packet
2060 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2063 CL_ParseServerMessage();
2066 // netquake control packets, supported for compatibility only
2067 if (length >= 5 && BuffBigLong(data) == ((int)NETFLAG_CTL | length) && !ENCRYPTION_REQUIRED)
2070 serverlist_info_t *info;
2074 SZ_Clear(&cl_message);
2075 SZ_Write(&cl_message, data, length);
2076 MSG_BeginReading(&cl_message);
2077 c = MSG_ReadByte(&cl_message);
2081 if (developer_extra.integer)
2082 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
2083 if (cls.connect_trying)
2085 lhnetaddress_t clientportaddress;
2086 clientportaddress = *peeraddress;
2087 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong(&cl_message));
2088 // extra ProQuake stuff
2090 cls.proquake_servermod = MSG_ReadByte(&cl_message); // MOD_PROQUAKE
2092 cls.proquake_servermod = 0;
2094 cls.proquake_serverversion = MSG_ReadByte(&cl_message); // version * 10
2096 cls.proquake_serverversion = 0;
2098 cls.proquake_serverflags = MSG_ReadByte(&cl_message); // flags (mainly PQF_CHEATFREE)
2100 cls.proquake_serverflags = 0;
2101 if (cls.proquake_servermod == 1)
2102 Con_Printf("Connected to ProQuake %.1f server, enabling precise aim\n", cls.proquake_serverversion / 10.0f);
2103 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
2104 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
2105 M_Update_Return_Reason("Accepted");
2106 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
2110 if (developer_extra.integer)
2111 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
2112 cls.connect_trying = false;
2113 M_Update_Return_Reason((char *)MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)));
2115 case CCREP_SERVER_INFO:
2116 if (developer_extra.integer)
2117 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
2118 // LordHavoc: because the quake server may report weird addresses
2119 // we just ignore it and keep the real address
2120 MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
2121 // search the cache for this server and update it
2122 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2126 info = &serverlist_cache[n].info;
2127 strlcpy(info->game, "Quake", sizeof(info->game));
2128 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
2129 strlcpy(info->name, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(info->name));
2130 strlcpy(info->map , MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(info->map));
2131 info->numplayers = MSG_ReadByte(&cl_message);
2132 info->maxplayers = MSG_ReadByte(&cl_message);
2133 info->protocol = MSG_ReadByte(&cl_message);
2135 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2138 case CCREP_RCON: // RocketGuy: ProQuake rcon support
2139 if (developer_extra.integer)
2140 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
2142 Con_Printf("%s\n", MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)));
2144 case CCREP_PLAYER_INFO:
2145 // we got a CCREP_PLAYER_INFO??
2146 //if (developer_extra.integer)
2147 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
2149 case CCREP_RULE_INFO:
2150 // we got a CCREP_RULE_INFO??
2151 //if (developer_extra.integer)
2152 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
2157 SZ_Clear(&cl_message);
2158 // we may not have liked the packet, but it was a valid control
2159 // packet, so we're done processing this packet now
2163 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2164 CL_ParseServerMessage();
2168 void NetConn_QueryQueueFrame(void)
2174 static double querycounter = 0;
2176 if(!net_slist_pause.integer && serverlist_paused)
2177 ServerList_RebuildViewList();
2178 serverlist_paused = net_slist_pause.integer != 0;
2180 if (serverlist_querysleep)
2183 // apply a cool down time after master server replies,
2184 // to avoid messing up the ping times on the servers
2185 if (serverlist_querywaittime > realtime)
2188 // each time querycounter reaches 1.0 issue a query
2189 querycounter += cl.realframetime * net_slist_queriespersecond.value;
2190 maxqueries = (int)querycounter;
2191 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2192 querycounter -= maxqueries;
2194 if( maxqueries == 0 ) {
2198 // scan serverlist and issue queries as needed
2199 serverlist_querysleep = true;
2201 timeouttime = realtime - net_slist_timeout.value;
2202 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
2204 serverlist_entry_t *entry = &serverlist_cache[ index ];
2205 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2210 serverlist_querysleep = false;
2211 if( entry->querycounter != 0 && entry->querytime > timeouttime )
2216 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
2218 lhnetaddress_t address;
2221 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2222 if (entry->protocol == PROTOCOL_QUAKEWORLD)
2224 for (socket = 0; socket < cl_numsockets ; socket++)
2225 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2229 for (socket = 0; socket < cl_numsockets ; socket++)
2230 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2233 // update the entry fields
2234 entry->querytime = realtime;
2235 entry->querycounter++;
2237 // if not in the slist menu we should print the server to console
2238 if (serverlist_consoleoutput)
2239 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2245 // have we tried to refresh this server?
2246 if( entry->query == SQS_REFRESHING ) {
2247 // yes, so update the reply count (since its not responding anymore)
2249 if(!serverlist_paused)
2250 ServerList_ViewList_Remove(entry);
2252 entry->query = SQS_TIMEDOUT;
2257 void NetConn_ClientFrame(void)
2260 lhnetaddress_t peeraddress;
2261 unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
2262 NetConn_UpdateSockets();
2263 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2265 if (cls.connect_remainingtries == 0)
2266 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2267 cls.connect_nextsendtime = realtime + 1;
2268 cls.connect_remainingtries--;
2269 if (cls.connect_remainingtries <= -10)
2271 cls.connect_trying = false;
2272 M_Update_Return_Reason("Connect: Failed");
2275 // try challenge first (newer DP server or QW)
2276 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2277 // then try netquake as a fallback (old server, or netquake)
2278 SZ_Clear(&cl_message);
2279 // save space for the header, filled in later
2280 MSG_WriteLong(&cl_message, 0);
2281 MSG_WriteByte(&cl_message, CCREQ_CONNECT);
2282 MSG_WriteString(&cl_message, "QUAKE");
2283 MSG_WriteByte(&cl_message, NET_PROTOCOL_VERSION);
2284 // extended proquake stuff
2285 MSG_WriteByte(&cl_message, 1); // mod = MOD_PROQUAKE
2286 // this version matches ProQuake 3.40, the first version to support
2287 // the NAT fix, and it only supports the NAT fix for ProQuake 3.40 or
2288 // higher clients, so we pretend we are that version...
2289 MSG_WriteByte(&cl_message, 34); // version * 10
2290 MSG_WriteByte(&cl_message, 0); // flags
2291 MSG_WriteLong(&cl_message, 0); // password
2292 // write the packetsize now...
2293 StoreBigLong(cl_message.data, NETFLAG_CTL | (cl_message.cursize & NETFLAG_LENGTH_MASK));
2294 NetConn_Write(cls.connect_mysocket, cl_message.data, cl_message.cursize, &cls.connect_address);
2295 SZ_Clear(&cl_message);
2297 for (i = 0;i < cl_numsockets;i++)
2299 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2301 // R_TimeReport("clientreadnetwork");
2302 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2303 // R_TimeReport("clientparsepacket");
2306 NetConn_QueryQueueFrame();
2307 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2309 Con_Print("Connection timed out\n");
2311 SV_LockThreadMutex();
2312 Host_ShutdownServer ();
2313 SV_UnlockThreadMutex();
2317 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2321 for (i = 0;i < bufferlength - 1;i++)
2325 c = rand () % (127 - 33) + 33;
2326 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2332 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2333 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2335 prvm_prog_t *prog = SVVM_prog;
2337 unsigned int nb_clients = 0, nb_bots = 0, i;
2340 const char *crypto_idstring;
2343 // How many clients are there?
2344 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2346 if (svs.clients[i].active)
2349 if (!svs.clients[i].netconnection)
2355 str = PRVM_GetString(prog, PRVM_serverglobalstring(worldstatus));
2361 for(q = str; *q && (size_t)(p - qcstatus) < (sizeof(qcstatus) - 1); ++q)
2362 if(*q != '\\' && *q != '\n')
2367 /// \TODO: we should add more information for the full status string
2368 crypto_idstring = Crypto_GetInfoResponseDataString();
2369 length = dpsnprintf(out_msg, out_size,
2370 "\377\377\377\377%s\x0A"
2371 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2372 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2377 fullstatus ? "statusResponse" : "infoResponse",
2378 gamename, com_modname, gameversion.integer, svs.maxclients,
2379 nb_clients, nb_bots, sv.worldbasename, hostname.string, NET_PROTOCOL_VERSION,
2380 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2381 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2382 crypto_idstring ? "\\d0_blind_id\\" : "", crypto_idstring ? crypto_idstring : "",
2383 fullstatus ? "\n" : "");
2385 // Make sure it fits in the buffer
2395 savelength = length;
2397 ptr = out_msg + length;
2398 left = (int)out_size - length;
2400 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2402 client_t *cl = &svs.clients[i];
2405 int nameind, cleanind, pingvalue;
2407 char cleanname [sizeof(cl->name)];
2411 // Remove all characters '"' and '\' in the player name
2416 curchar = cl->name[nameind++];
2417 if (curchar != '"' && curchar != '\\')
2419 cleanname[cleanind++] = curchar;
2420 if (cleanind == sizeof(cleanname) - 1)
2423 } while (curchar != '\0');
2424 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2426 pingvalue = (int)(cl->ping * 1000.0f);
2427 if(cl->netconnection)
2428 pingvalue = bound(1, pingvalue, 9999);
2433 ed = PRVM_EDICT_NUM(i + 1);
2434 str = PRVM_GetString(prog, PRVM_serveredictstring(ed, clientstatus));
2440 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2441 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2446 if ((gamemode == GAME_NEXUIZ || gamemode == GAME_XONOTIC) && (teamplay.integer > 0))
2448 if(cl->frags == -666) // spectator
2449 strlcpy(teambuf, " 0", sizeof(teambuf));
2450 else if(cl->colors == 0x44) // red team
2451 strlcpy(teambuf, " 1", sizeof(teambuf));
2452 else if(cl->colors == 0xDD) // blue team
2453 strlcpy(teambuf, " 2", sizeof(teambuf));
2454 else if(cl->colors == 0xCC) // yellow team
2455 strlcpy(teambuf, " 3", sizeof(teambuf));
2456 else if(cl->colors == 0x99) // pink team
2457 strlcpy(teambuf, " 4", sizeof(teambuf));
2459 strlcpy(teambuf, " 0", sizeof(teambuf));
2464 // note: team number is inserted according to SoF2 protocol
2466 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2472 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2481 // turn it into an infoResponse!
2482 out_msg[savelength] = 0;
2483 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2484 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2499 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2501 int floodslotnum, bestfloodslotnum;
2502 double bestfloodtime;
2503 lhnetaddress_t noportpeeraddress;
2504 // see if this is a connect flood
2505 noportpeeraddress = *peeraddress;
2506 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2507 bestfloodslotnum = 0;
2508 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2509 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2511 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2513 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2514 bestfloodslotnum = floodslotnum;
2516 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2518 // this address matches an ongoing flood address
2519 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2521 // renew the ban on this address so it does not expire
2522 // until the flood has subsided
2523 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2524 //Con_Printf("Flood detected!\n");
2527 // the flood appears to have subsided, so allow this
2528 bestfloodslotnum = floodslotnum; // reuse the same slot
2532 // begin a new timeout on this address
2533 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2534 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2535 //Con_Printf("Flood detection initiated!\n");
2539 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2542 lhnetaddress_t noportpeeraddress;
2543 // see if this is a connect flood
2544 noportpeeraddress = *peeraddress;
2545 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2546 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2548 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2550 // this address matches an ongoing flood address
2552 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2553 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2554 //Con_Printf("Flood cleared!\n");
2559 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2561 static qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2566 t1 = (long) time(NULL);
2567 t2 = strtol(s, NULL, 0);
2568 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2571 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2574 return !memcmp(mdfourbuf, hash, 16);
2577 static qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2582 if(slen < (int)(sizeof(challenge[0].string)) - 1)
2585 // validate the challenge
2586 for (i = 0;i < MAX_CHALLENGES;i++)
2587 if(challenge[i].time > 0)
2588 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2590 // if the challenge is not recognized, drop the packet
2591 if (i == MAX_CHALLENGES)
2594 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2597 if(memcmp(mdfourbuf, hash, 16))
2600 // unmark challenge to prevent replay attacks
2601 challenge[i].time = 0;
2606 static qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2608 return !strcmp(password, hash);
2611 /// returns a string describing the user level, or NULL for auth failure
2612 static const char *RCon_Authenticate(lhnetaddress_t *peeraddress, const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2614 const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2615 static char buf[MAX_INPUTLINE];
2617 qboolean restricted = false;
2618 qboolean have_usernames = false;
2621 userpass_start = rcon_password.string;
2622 while((userpass_end = strchr(userpass_start, ' ')))
2624 have_usernames = true;
2625 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2627 if(comparator(peeraddress, buf, password, cs, cslen))
2629 userpass_start = userpass_end + 1;
2631 if(userpass_start[0])
2633 userpass_end = userpass_start + strlen(userpass_start);
2634 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2639 have_usernames = false;
2640 userpass_start = rcon_restricted_password.string;
2641 while((userpass_end = strchr(userpass_start, ' ')))
2643 have_usernames = true;
2644 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2646 if(comparator(peeraddress, buf, password, cs, cslen))
2648 userpass_start = userpass_end + 1;
2650 if(userpass_start[0])
2652 userpass_end = userpass_start + strlen(userpass_start);
2653 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2657 return NULL; // DENIED
2660 for(text = s; text != endpos; ++text)
2661 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2662 return NULL; // block possible exploits against the parser/alias expansion
2666 size_t l = strlen(s);
2669 hasquotes = (strchr(s, '"') != NULL);
2670 // sorry, we can't allow these substrings in wildcard expressions,
2671 // as they can mess with the argument counts
2672 text = rcon_restricted_commands.string;
2673 while(COM_ParseToken_Console(&text))
2675 // com_token now contains a pattern to check for...
2676 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2679 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2682 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2684 if(!strcmp(com_token, s))
2687 else // single-arg expression? must match the beginning of the command
2689 if(!strcmp(com_token, s))
2691 if(!memcmp(va(vabuf, sizeof(vabuf), "%s ", com_token), s, strlen(com_token) + 1))
2695 // if we got here, nothing matched!
2703 userpass_startpass = strchr(userpass_start, ':');
2704 if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2705 return va(vabuf, sizeof(vabuf), "%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2707 return va(vabuf, sizeof(vabuf), "%srcon", restricted ? "restricted " : "");
2710 static void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos, qboolean proquakeprotocol)
2714 // looks like a legitimate rcon command with the correct password
2715 const char *s_ptr = s;
2716 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2717 while(s_ptr != endpos)
2719 size_t l = strlen(s_ptr);
2721 Con_Printf(" %s;", s_ptr);
2726 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2727 Con_Rcon_Redirect_Init(mysocket, peeraddress, proquakeprotocol);
2730 size_t l = strlen(s);
2733 client_t *host_client_save = host_client;
2734 Cmd_ExecuteString(s, src_command, true);
2735 host_client = host_client_save;
2736 // in case it is a command that changes host_client (like restart)
2740 Con_Rcon_Redirect_End();
2744 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2748 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2750 int i, ret, clientnum, best;
2753 char *s, *string, response[1400], addressstring2[128];
2754 static char stringbuf[16384]; // server only
2755 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2756 char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
2757 size_t sendlength, response_len;
2758 char infostringvalue[MAX_INPUTLINE];
2764 // convert the address to a string incase we need it
2765 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2767 // see if we can identify the sender as a local player
2768 // (this is necessary for rcon to send a reliable reply if the client is
2769 // actually on the server, not sending remotely)
2770 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2771 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2773 if (i == svs.maxclients)
2776 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2778 // received a command string - strip off the packaging and put it
2779 // into our string buffer with NULL termination
2782 length = min(length, (int)sizeof(stringbuf) - 1);
2783 memcpy(stringbuf, data, length);
2784 stringbuf[length] = 0;
2787 if (developer_extra.integer)
2789 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2790 Com_HexDumpToConsole(data, length);
2793 sendlength = sizeof(senddata) - 4;
2794 switch(Crypto_ServerParsePacket(string, length, senddata+4, &sendlength, peeraddress))
2796 case CRYPTO_NOMATCH:
2802 memcpy(senddata, "\377\377\377\377", 4);
2803 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2806 case CRYPTO_DISCARD:
2809 memcpy(senddata, "\377\377\377\377", 4);
2810 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2814 case CRYPTO_REPLACE:
2815 string = senddata+4;
2816 length = sendlength;
2820 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -3))
2822 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2824 if(challenge[i].time > 0)
2825 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2827 if (besttime > challenge[i].time)
2828 besttime = challenge[best = i].time;
2830 // if we did not find an exact match, choose the oldest and
2831 // update address and string
2832 if (i == MAX_CHALLENGES)
2835 challenge[i].address = *peeraddress;
2836 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2838 challenge[i].time = realtime;
2839 // send the challenge
2840 dpsnprintf(response, sizeof(response), "\377\377\377\377challenge %s", challenge[i].string);
2841 response_len = strlen(response) + 1;
2842 Crypto_ServerAppendToChallenge(string, length, response, &response_len, sizeof(response));
2843 NetConn_Write(mysocket, response, response_len, peeraddress);
2846 if (length > 8 && !memcmp(string, "connect\\", 8))
2848 crypto_t *crypto = Crypto_ServerGetInstance(peeraddress);
2852 if(crypto && crypto->authenticated)
2854 // no need to check challenge
2855 if(crypto_developer.integer)
2857 Con_Printf("%s connection to %s is being established: client is %s@%.*s, I am %.*s@%.*s\n",
2858 crypto->use_aes ? "Encrypted" : "Authenticated",
2860 crypto->client_idfp[0] ? crypto->client_idfp : "-",
2861 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-",
2862 crypto_keyfp_recommended_length, crypto->server_idfp[0] ? crypto->server_idfp : "-",
2863 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-"
2869 if ((s = InfoString_GetValue(string, "challenge", infostringvalue, sizeof(infostringvalue))))
2871 // validate the challenge
2872 for (i = 0;i < MAX_CHALLENGES;i++)
2873 if(challenge[i].time > 0)
2874 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2876 // if the challenge is not recognized, drop the packet
2877 if (i == MAX_CHALLENGES)
2882 if((s = InfoString_GetValue(string, "message", infostringvalue, sizeof(infostringvalue))))
2883 Con_DPrintf("Connecting client %s sent us the message: %s\n", addressstring2, s);
2885 if(!(islocal || sv_public.integer > -2))
2887 if (developer_extra.integer)
2888 Con_Printf("Datagram_ParseConnectionless: sending \"reject %s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
2889 NetConn_WriteString(mysocket, va(vabuf, sizeof(vabuf), "\377\377\377\377reject %s", sv_public_rejectreason.string), peeraddress);
2893 // check engine protocol
2894 if(!(s = InfoString_GetValue(string, "protocol", infostringvalue, sizeof(infostringvalue))) || strcmp(s, "darkplaces 3"))
2896 if (developer_extra.integer)
2897 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2898 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2902 // see if this is a duplicate connection request or a disconnected
2903 // client who is rejoining to the same client slot
2904 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2906 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2908 // this is a known client...
2909 if(crypto && crypto->authenticated)
2911 // reject if changing key!
2912 if(client->netconnection->crypto.authenticated)
2915 strcmp(client->netconnection->crypto.client_idfp, crypto->client_idfp)
2917 strcmp(client->netconnection->crypto.server_idfp, crypto->server_idfp)
2919 strcmp(client->netconnection->crypto.client_keyfp, crypto->client_keyfp)
2921 strcmp(client->netconnection->crypto.server_keyfp, crypto->server_keyfp)
2924 if (developer_extra.integer)
2925 Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to change key of crypto.\" to %s.\n", addressstring2);
2926 NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to change key of crypto.", peeraddress);
2933 // reject if downgrading!
2934 if(client->netconnection->crypto.authenticated)
2936 if (developer_extra.integer)
2937 Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to downgrade crypto.\" to %s.\n", addressstring2);
2938 NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to downgrade crypto.", peeraddress);
2942 if (client->spawned)
2944 // client crashed and is coming back,
2945 // keep their stuff intact
2946 if (developer_extra.integer)
2947 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2948 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2949 if(crypto && crypto->authenticated)
2950 Crypto_ServerFinishInstance(&client->netconnection->crypto, crypto);
2951 SV_SendServerinfo(client);
2955 // client is still trying to connect,
2956 // so we send a duplicate reply
2957 if (developer_extra.integer)
2958 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2959 if(crypto && crypto->authenticated)
2960 Crypto_ServerFinishInstance(&client->netconnection->crypto, crypto);
2961 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2967 if (NetConn_PreventConnectFlood(peeraddress))
2970 // find an empty client slot for this new client
2971 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2974 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2976 // allocated connection
2977 if (developer_extra.integer)
2978 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2979 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2980 // now set up the client
2981 if(crypto && crypto->authenticated)
2982 Crypto_ServerFinishInstance(&conn->crypto, crypto);
2983 SV_ConnectClient(clientnum, conn);
2984 NetConn_Heartbeat(1);
2989 // no empty slots found - server is full
2990 if (developer_extra.integer)
2991 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2992 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2996 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2998 const char *challenge = NULL;
3000 // If there was a challenge in the getinfo message
3001 if (length > 8 && string[7] == ' ')
3002 challenge = string + 8;
3004 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
3006 if (developer_extra.integer)
3007 Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
3008 NetConn_WriteString(mysocket, response, peeraddress);
3012 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
3014 const char *challenge = NULL;
3016 // If there was a challenge in the getinfo message
3017 if (length > 10 && string[9] == ' ')
3018 challenge = string + 10;
3020 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
3022 if (developer_extra.integer)
3023 Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
3024 NetConn_WriteString(mysocket, response, peeraddress);
3028 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
3030 char *password = string + 20;
3031 char *timeval = string + 37;
3032 char *s = strchr(timeval, ' ');
3033 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3034 const char *userlevel;
3036 if(rcon_secure.integer > 1)
3040 return true; // invalid packet
3043 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
3044 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3047 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
3049 char *password = string + 25;
3050 char *challenge = string + 42;
3051 char *s = strchr(challenge, ' ');
3052 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3053 const char *userlevel;
3055 return true; // invalid packet
3058 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
3059 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3062 if (length >= 5 && !memcmp(string, "rcon ", 5))
3065 char *s = string + 5;
3066 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3069 if(rcon_secure.integer > 0)
3072 for (i = 0;!ISWHITESPACE(*s);s++)
3073 if (i < (int)sizeof(password) - 1)
3075 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
3078 if (!ISWHITESPACE(password[0]))
3080 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3081 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3085 if (!strncmp(string, "extResponse ", 12))
3087 ++sv_net_extresponse_count;
3088 if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
3089 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
3090 sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
3091 dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
3094 if (!strncmp(string, "ping", 4))
3096 if (developer_extra.integer)
3097 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
3098 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
3101 if (!strncmp(string, "ack", 3))
3103 // we may not have liked the packet, but it was a command packet, so
3104 // we're done processing this packet now
3107 // netquake control packets, supported for compatibility only, and only
3108 // when running game protocols that are normally served via this connection
3110 // (this protects more modern protocols against being used for
3111 // Quake packet flood Denial Of Service attacks)
3112 if (length >= 5 && (i = BuffBigLong(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) && !ENCRYPTION_REQUIRED)
3116 const char *protocolname;
3119 SZ_Clear(&sv_message);
3120 SZ_Write(&sv_message, data, length);
3121 MSG_BeginReading(&sv_message);
3122 c = MSG_ReadByte(&sv_message);
3126 if (developer_extra.integer)
3127 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
3128 if(!(islocal || sv_public.integer > -2))
3130 if (developer_extra.integer)
3131 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"%s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
3132 SZ_Clear(&sv_message);
3133 // save space for the header, filled in later
3134 MSG_WriteLong(&sv_message, 0);
3135 MSG_WriteByte(&sv_message, CCREP_REJECT);
3136 MSG_WriteString(&sv_message, va(vabuf, sizeof(vabuf), "%s\n", sv_public_rejectreason.string));
3137 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3138 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3139 SZ_Clear(&sv_message);
3143 protocolname = MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring));
3144 protocolnumber = MSG_ReadByte(&sv_message);
3145 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
3147 if (developer_extra.integer)
3148 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
3149 SZ_Clear(&sv_message);
3150 // save space for the header, filled in later
3151 MSG_WriteLong(&sv_message, 0);
3152 MSG_WriteByte(&sv_message, CCREP_REJECT);
3153 MSG_WriteString(&sv_message, "Incompatible version.\n");
3154 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3155 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3156 SZ_Clear(&sv_message);
3160 // see if this connect request comes from a known client
3161 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3163 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
3165 // this is either a duplicate connection request
3166 // or coming back from a timeout
3167 // (if so, keep their stuff intact)
3170 if (developer_extra.integer)
3171 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
3172 SZ_Clear(&sv_message);
3173 // save space for the header, filled in later
3174 MSG_WriteLong(&sv_message, 0);
3175 MSG_WriteByte(&sv_message, CCREP_ACCEPT);
3176 MSG_WriteLong(&sv_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
3177 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3178 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3179 SZ_Clear(&sv_message);
3181 // if client is already spawned, re-send the
3182 // serverinfo message as they'll need it to play
3183 if (client->spawned)
3184 SV_SendServerinfo(client);
3189 // this is a new client, check for connection flood
3190 if (NetConn_PreventConnectFlood(peeraddress))
3193 // find a slot for the new client
3194 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3197 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
3199 // connect to the client
3200 // everything is allocated, just fill in the details
3201 strlcpy (conn->address, addressstring2, sizeof (conn->address));
3202 if (developer_extra.integer)
3203 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
3204 // send back the info about the server connection
3205 SZ_Clear(&sv_message);
3206 // save space for the header, filled in later
3207 MSG_WriteLong(&sv_message, 0);
3208 MSG_WriteByte(&sv_message, CCREP_ACCEPT);
3209 MSG_WriteLong(&sv_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
3210 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3211 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3212 SZ_Clear(&sv_message);
3213 // now set up the client struct
3214 SV_ConnectClient(clientnum, conn);
3215 NetConn_Heartbeat(1);
3220 if (developer_extra.integer)
3221 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
3222 // no room; try to let player know
3223 SZ_Clear(&sv_message);
3224 // save space for the header, filled in later
3225 MSG_WriteLong(&sv_message, 0);
3226 MSG_WriteByte(&sv_message, CCREP_REJECT);
3227 MSG_WriteString(&sv_message, "Server is full.\n");
3228 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3229 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3230 SZ_Clear(&sv_message);
3232 case CCREQ_SERVER_INFO:
3233 if (developer_extra.integer)
3234 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
3235 if(!(islocal || sv_public.integer > -1))
3237 if (sv.active && !strcmp(MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), "QUAKE"))
3240 char myaddressstring[128];
3241 if (developer_extra.integer)
3242 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
3243 SZ_Clear(&sv_message);
3244 // save space for the header, filled in later
3245 MSG_WriteLong(&sv_message, 0);
3246 MSG_WriteByte(&sv_message, CCREP_SERVER_INFO);
3247 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
3248 MSG_WriteString(&sv_message, myaddressstring);
3249 MSG_WriteString(&sv_message, hostname.string);
3250 MSG_WriteString(&sv_message, sv.name);
3251 // How many clients are there?
3252 for (i = 0, numclients = 0;i < svs.maxclients;i++)
3253 if (svs.clients[i].active)
3255 MSG_WriteByte(&sv_message, numclients);
3256 MSG_WriteByte(&sv_message, svs.maxclients);
3257 MSG_WriteByte(&sv_message, NET_PROTOCOL_VERSION);
3258 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3259 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3260 SZ_Clear(&sv_message);
3263 case CCREQ_PLAYER_INFO:
3264 if (developer_extra.integer)
3265 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
3266 if(!(islocal || sv_public.integer > -1))
3270 int playerNumber, activeNumber, clientNumber;
3273 playerNumber = MSG_ReadByte(&sv_message);
3275 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3276 if (client->active && ++activeNumber == playerNumber)
3278 if (clientNumber != svs.maxclients)
3280 SZ_Clear(&sv_message);
3281 // save space for the header, filled in later
3282 MSG_WriteLong(&sv_message, 0);
3283 MSG_WriteByte(&sv_message, CCREP_PLAYER_INFO);
3284 MSG_WriteByte(&sv_message, playerNumber);
3285 MSG_WriteString(&sv_message, client->name);
3286 MSG_WriteLong(&sv_message, client->colors);
3287 MSG_WriteLong(&sv_message, client->frags);
3288 MSG_WriteLong(&sv_message, (int)(realtime - client->connecttime));
3289 if(sv_status_privacy.integer)
3290 MSG_WriteString(&sv_message, client->netconnection ? "hidden" : "botclient");
3292 MSG_WriteString(&sv_message, client->netconnection ? client->netconnection->address : "botclient");
3293 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3294 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3295 SZ_Clear(&sv_message);
3299 case CCREQ_RULE_INFO:
3300 if (developer_extra.integer)
3301 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3302 if(!(islocal || sv_public.integer > -1))
3309 // find the search start location
3310 prevCvarName = MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring));
3311 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3313 // send the response
3314 SZ_Clear(&sv_message);
3315 // save space for the header, filled in later
3316 MSG_WriteLong(&sv_message, 0);
3317 MSG_WriteByte(&sv_message, CCREP_RULE_INFO);
3320 MSG_WriteString(&sv_message, var->name);
3321 MSG_WriteString(&sv_message, var->string);
3323 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3324 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3325 SZ_Clear(&sv_message);
3329 if (developer_extra.integer)
3330 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RCON from %s.\n", addressstring2);
3331 if (sv.active && !rcon_secure.integer)
3333 char password[2048];
3337 const char *userlevel;
3338 strlcpy(password, MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), sizeof(password));
3339 strlcpy(cmd, MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), sizeof(cmd));
3341 endpos = cmd + strlen(cmd) + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3342 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3343 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, true);
3350 SZ_Clear(&sv_message);
3351 // we may not have liked the packet, but it was a valid control
3352 // packet, so we're done processing this packet now
3357 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3359 SV_ReadClientMessage();
3366 void NetConn_ServerFrame(void)
3369 lhnetaddress_t peeraddress;
3370 unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
3371 for (i = 0;i < sv_numsockets;i++)
3372 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3373 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3374 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3376 // never timeout loopback connections
3377 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3379 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3380 SV_DropClient(false);
3385 void NetConn_SleepMicroseconds(int microseconds)
3387 LHNET_SleepUntilPacket_Microseconds(microseconds);
3390 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3394 lhnetaddress_t masteraddress;
3395 lhnetaddress_t broadcastaddress;
3398 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3401 // 26000 is the default quake server port, servers on other ports will not
3403 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3404 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3408 for (i = 0;i < cl_numsockets;i++)
3412 const char *cmdname, *extraoptions;
3413 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3415 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3417 // search LAN for Quake servers
3418 SZ_Clear(&cl_message);
3419 // save space for the header, filled in later
3420 MSG_WriteLong(&cl_message, 0);
3421 MSG_WriteByte(&cl_message, CCREQ_SERVER_INFO);
3422 MSG_WriteString(&cl_message, "QUAKE");
3423 MSG_WriteByte(&cl_message, NET_PROTOCOL_VERSION);
3424 StoreBigLong(cl_message.data, NETFLAG_CTL | (cl_message.cursize & NETFLAG_LENGTH_MASK));
3425 NetConn_Write(cl_sockets[i], cl_message.data, cl_message.cursize, &broadcastaddress);
3426 SZ_Clear(&cl_message);
3428 // search LAN for DarkPlaces servers
3429 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3432 // build the getservers message to send to the dpmaster master servers
3433 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3435 cmdname = "getserversExt";
3436 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
3440 cmdname = "getservers";
3443 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3446 for (masternum = 0;sv_masters[masternum].name;masternum++)
3448 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3451 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3455 // search favorite servers
3456 for(j = 0; j < nFavorites; ++j)
3458 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3460 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3461 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3468 // only query QuakeWorld servers when the user wants to
3471 for (i = 0;i < cl_numsockets;i++)
3475 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3477 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3479 // search LAN for QuakeWorld servers
3480 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3482 // build the getservers message to send to the qwmaster master servers
3483 // note this has no -1 prefix, and the trailing nul byte is sent
3484 dpsnprintf(request, sizeof(request), "c\n");
3488 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3490 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3492 if (m_state != m_slist)
3494 char lookupstring[128];
3495 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3496 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3499 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3503 // search favorite servers
3504 for(j = 0; j < nFavorites; ++j)
3506 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3508 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3510 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3511 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3518 if (!masterquerycount)
3520 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3521 M_Update_Return_Reason("No network");
3525 void NetConn_Heartbeat(int priority)
3527 lhnetaddress_t masteraddress;
3529 lhnetsocket_t *mysocket;
3531 // if it's a state change (client connected), limit next heartbeat to no
3532 // more than 30 sec in the future
3533 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3534 nextheartbeattime = realtime + 30.0;
3536 // limit heartbeatperiod to 30 to 270 second range,
3537 // lower limit is to avoid abusing master servers with excess traffic,
3538 // upper limit is to avoid timing out on the master server (which uses
3540 if (sv_heartbeatperiod.value < 30)
3541 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3542 if (sv_heartbeatperiod.value > 270)
3543 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3545 // make advertising optional and don't advertise singleplayer games, and
3546 // only send a heartbeat as often as the admin wants
3547 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3549 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3550 for (masternum = 0;sv_masters[masternum].name;masternum++)
3551 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3552 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3556 static void Net_Heartbeat_f(void)
3559 NetConn_Heartbeat(2);
3561 Con_Print("No server running, can not heartbeat to master server.\n");
3564 static void PrintStats(netconn_t *conn)
3566 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3567 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3569 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3570 Con_Printf("unreliable messages sent = %i\n", conn->unreliableMessagesSent);
3571 Con_Printf("unreliable messages recv = %i\n", conn->unreliableMessagesReceived);
3572 Con_Printf("reliable messages sent = %i\n", conn->reliableMessagesSent);
3573 Con_Printf("reliable messages received = %i\n", conn->reliableMessagesReceived);
3574 Con_Printf("packetsSent = %i\n", conn->packetsSent);
3575 Con_Printf("packetsReSent = %i\n", conn->packetsReSent);
3576 Con_Printf("packetsReceived = %i\n", conn->packetsReceived);
3577 Con_Printf("receivedDuplicateCount = %i\n", conn->receivedDuplicateCount);
3578 Con_Printf("droppedDatagrams = %i\n", conn->droppedDatagrams);
3581 void Net_Stats_f(void)
3584 Con_Print("connections =\n");
3585 for (conn = netconn_list;conn;conn = conn->next)
3589 void Net_Refresh_f(void)
3591 if (m_state != m_slist) {
3592 Con_Print("Sending new requests to master servers\n");
3593 ServerList_QueryList(false, true, false, true);
3594 Con_Print("Listening for replies...\n");
3596 ServerList_QueryList(false, true, false, false);
3599 void Net_Slist_f(void)
3601 ServerList_ResetMasks();
3602 serverlist_sortbyfield = SLIF_PING;
3603 serverlist_sortflags = 0;
3604 if (m_state != m_slist) {
3605 Con_Print("Sending requests to master servers\n");
3606 ServerList_QueryList(true, true, false, true);
3607 Con_Print("Listening for replies...\n");
3609 ServerList_QueryList(true, true, false, false);
3612 void Net_SlistQW_f(void)
3614 ServerList_ResetMasks();
3615 serverlist_sortbyfield = SLIF_PING;
3616 serverlist_sortflags = 0;
3617 if (m_state != m_slist) {
3618 Con_Print("Sending requests to master servers\n");
3619 ServerList_QueryList(true, false, true, true);
3620 serverlist_consoleoutput = true;
3621 Con_Print("Listening for replies...\n");
3623 ServerList_QueryList(true, false, true, false);
3626 void NetConn_Init(void)
3629 lhnetaddress_t tempaddress;
3630 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3631 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3632 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3633 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3634 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3635 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3636 Cvar_RegisterVariable(&rcon_restricted_password);
3637 Cvar_RegisterVariable(&rcon_restricted_commands);
3638 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3639 Cvar_RegisterVariable(&net_slist_queriespersecond);
3640 Cvar_RegisterVariable(&net_slist_queriesperframe);
3641 Cvar_RegisterVariable(&net_slist_timeout);
3642 Cvar_RegisterVariable(&net_slist_maxtries);
3643 Cvar_RegisterVariable(&net_slist_favorites);
3644 Cvar_RegisterVariable(&net_slist_pause);
3645 Cvar_RegisterVariable(&net_messagetimeout);
3646 Cvar_RegisterVariable(&net_connecttimeout);
3647 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3648 Cvar_RegisterVariable(&cl_netlocalping);
3649 Cvar_RegisterVariable(&cl_netpacketloss_send);
3650 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3651 Cvar_RegisterVariable(&hostname);
3652 Cvar_RegisterVariable(&developer_networking);
3653 Cvar_RegisterVariable(&cl_netport);
3654 Cvar_RegisterVariable(&sv_netport);
3655 Cvar_RegisterVariable(&net_address);
3656 Cvar_RegisterVariable(&net_address_ipv6);
3657 Cvar_RegisterVariable(&sv_public);
3658 Cvar_RegisterVariable(&sv_public_rejectreason);
3659 Cvar_RegisterVariable(&sv_heartbeatperiod);
3660 for (i = 0;sv_masters[i].name;i++)
3661 Cvar_RegisterVariable(&sv_masters[i]);
3662 Cvar_RegisterVariable(&gameversion);
3663 Cvar_RegisterVariable(&gameversion_min);
3664 Cvar_RegisterVariable(&gameversion_max);
3665 // 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.
3666 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3668 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3670 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3671 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3674 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3676 // 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
3677 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3679 i = atoi(com_argv[i + 1]);
3680 if (i >= 0 && i < 65536)
3682 Con_Printf("-port option used, setting port cvar to %i\n", i);
3683 Cvar_SetValueQuick(&sv_netport, i);
3686 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3690 cl_message.data = cl_message_buf;
3691 cl_message.maxsize = sizeof(cl_message_buf);
3692 cl_message.cursize = 0;
3693 sv_message.data = sv_message_buf;
3694 sv_message.maxsize = sizeof(sv_message_buf);
3695 sv_message.cursize = 0;
3697 if (Thread_HasThreads())
3698 netconn_mutex = Thread_CreateMutex();
3701 void NetConn_Shutdown(void)
3703 NetConn_CloseClientPorts();
3704 NetConn_CloseServerPorts();
3707 Thread_DestroyMutex(netconn_mutex);
3708 netconn_mutex = NULL;