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();
925 port = bound(0, cl_netport.integer, 65535);
926 if (cl_netport.integer != port)
927 Cvar_SetValueQuick(&cl_netport, port);
929 Con_Printf("Client using an automatically assigned port\n");
931 Con_Printf("Client using port %i\n", port);
932 NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
933 NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
935 NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
939 void NetConn_CloseServerPorts(void)
941 for (;sv_numsockets > 0;sv_numsockets--)
942 if (sv_sockets[sv_numsockets - 1])
943 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
946 static qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
948 lhnetaddress_t address;
951 char addressstring2[1024];
954 for (port = defaultport; port <= defaultport + range; port++)
956 if (addressstring && addressstring[0])
957 success = LHNETADDRESS_FromString(&address, addressstring, port);
959 success = LHNETADDRESS_FromPort(&address, addresstype, port);
962 if ((s = LHNET_OpenSocket_Connectionless(&address)))
964 sv_sockets[sv_numsockets++] = s;
965 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
966 if (addresstype != LHNETADDRESSTYPE_LOOP)
967 Con_Printf("Server listening on address %s\n", addressstring2);
972 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
973 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
978 Con_Printf("Server unable to parse address %s\n", addressstring);
979 // if it cant parse one address, it wont be able to parse another for sure
986 void NetConn_OpenServerPorts(int opennetports)
989 NetConn_CloseServerPorts();
990 NetConn_UpdateSockets();
991 port = bound(0, sv_netport.integer, 65535);
994 Con_Printf("Server using port %i\n", port);
995 if (sv_netport.integer != port)
996 Cvar_SetValueQuick(&sv_netport, port);
997 if (cls.state != ca_dedicated)
998 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
1002 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1003 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
1005 NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
1008 if (sv_numsockets == 0)
1009 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
1012 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
1014 int i, a = LHNETADDRESS_GetAddressType(address);
1015 for (i = 0;i < cl_numsockets;i++)
1016 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
1017 return cl_sockets[i];
1021 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
1023 int i, a = LHNETADDRESS_GetAddressType(address);
1024 for (i = 0;i < sv_numsockets;i++)
1025 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
1026 return sv_sockets[i];
1030 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
1033 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
1034 conn->mysocket = mysocket;
1035 conn->peeraddress = *peeraddress;
1036 conn->lastMessageTime = realtime;
1037 conn->message.data = conn->messagedata;
1038 conn->message.maxsize = sizeof(conn->messagedata);
1039 conn->message.cursize = 0;
1040 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
1041 // reduce effectiveness of connection request floods
1042 conn->timeout = realtime + net_connecttimeout.value;
1043 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
1044 conn->next = netconn_list;
1045 netconn_list = conn;
1049 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
1050 void NetConn_Close(netconn_t *conn)
1053 // remove connection from list
1055 // allow the client to reconnect immediately
1056 NetConn_ClearConnectFlood(&(conn->peeraddress));
1058 if (conn == netconn_list)
1059 netconn_list = conn->next;
1062 for (c = netconn_list;c;c = c->next)
1064 if (c->next == conn)
1066 c->next = conn->next;
1070 // not found in list, we'll avoid crashing here...
1078 static int clientport = -1;
1079 static int clientport2 = -1;
1080 static int hostport = -1;
1081 void NetConn_UpdateSockets(void)
1085 if (cls.state != ca_dedicated)
1087 if (clientport2 != cl_netport.integer)
1089 clientport2 = cl_netport.integer;
1090 if (cls.state == ca_connected)
1091 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1093 if (cls.state == ca_disconnected && clientport != clientport2)
1095 clientport = clientport2;
1096 NetConn_CloseClientPorts();
1098 if (cl_numsockets == 0)
1099 NetConn_OpenClientPorts();
1102 if (hostport != sv_netport.integer)
1104 hostport = sv_netport.integer;
1106 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1109 for (j = 0;j < MAX_RCONS;j++)
1111 i = (cls.rcon_ringpos + j + 1) % MAX_RCONS;
1112 if(cls.rcon_commands[i][0])
1114 if(realtime > cls.rcon_timeout[i])
1117 LHNETADDRESS_ToString(&cls.rcon_addresses[i], s, sizeof(s), true);
1118 Con_Printf("rcon to %s (for command %s) failed: challenge request timed out\n", s, cls.rcon_commands[i]);
1119 cls.rcon_commands[i][0] = 0;
1127 static int NetConn_ReceivedMessage(netconn_t *conn, const unsigned char *data, size_t length, protocolversion_t protocol, double newtimeout)
1129 int originallength = length;
1130 unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
1131 unsigned char cryptosendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1132 unsigned char cryptoreadbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1136 if (protocol == PROTOCOL_QUAKEWORLD)
1138 int sequence, sequence_ack;
1139 int reliable_ack, reliable_message;
1143 sequence = LittleLong(*((int *)(data + 0)));
1144 sequence_ack = LittleLong(*((int *)(data + 4)));
1148 if (conn != cls.netcon)
1153 // 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?)
1154 //qport = LittleShort(*((int *)(data + 8)));
1159 conn->packetsReceived++;
1160 reliable_message = (sequence >> 31) & 1;
1161 reliable_ack = (sequence_ack >> 31) & 1;
1162 sequence &= ~(1<<31);
1163 sequence_ack &= ~(1<<31);
1164 if (sequence <= conn->qw.incoming_sequence)
1166 //Con_DPrint("Got a stale datagram\n");
1169 count = sequence - (conn->qw.incoming_sequence + 1);
1172 conn->droppedDatagrams += count;
1173 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1176 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1177 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1178 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1179 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1180 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1183 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1184 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1185 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1186 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1187 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1188 if (reliable_ack == conn->qw.reliable_sequence)
1190 // received, now we will be able to send another reliable message
1191 conn->sendMessageLength = 0;
1192 conn->reliableMessagesReceived++;
1194 conn->qw.incoming_sequence = sequence;
1195 if (conn == cls.netcon)
1196 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1197 conn->qw.incoming_acknowledged = sequence_ack;
1198 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1199 if (reliable_message)
1200 conn->qw.incoming_reliable_sequence ^= 1;
1201 conn->lastMessageTime = realtime;
1202 conn->timeout = realtime + newtimeout;
1203 conn->unreliableMessagesReceived++;
1204 if (conn == cls.netcon)
1206 SZ_Clear(&cl_message);
1207 SZ_Write(&cl_message, data, length);
1208 MSG_BeginReading(&cl_message);
1212 SZ_Clear(&sv_message);
1213 SZ_Write(&sv_message, data, length);
1214 MSG_BeginReading(&sv_message);
1222 unsigned int sequence;
1227 originallength = length;
1228 data = (const unsigned char *) Crypto_DecryptPacket(&conn->crypto, data, length, cryptoreadbuffer, &length, sizeof(cryptoreadbuffer));
1234 qlength = (unsigned int)BuffBigLong(data);
1235 flags = qlength & ~NETFLAG_LENGTH_MASK;
1236 qlength &= NETFLAG_LENGTH_MASK;
1237 // control packets were already handled
1238 if (!(flags & NETFLAG_CTL) && qlength == length)
1240 sequence = BuffBigLong(data + 4);
1241 conn->packetsReceived++;
1244 if (flags & NETFLAG_UNRELIABLE)
1246 if (sequence >= conn->nq.unreliableReceiveSequence)
1248 if (sequence > conn->nq.unreliableReceiveSequence)
1250 count = sequence - conn->nq.unreliableReceiveSequence;
1251 conn->droppedDatagrams += count;
1252 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1255 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1256 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1257 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1258 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1259 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1262 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1263 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1264 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1265 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1266 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1267 conn->nq.unreliableReceiveSequence = sequence + 1;
1268 conn->lastMessageTime = realtime;
1269 conn->timeout = realtime + newtimeout;
1270 conn->unreliableMessagesReceived++;
1273 if (conn == cls.netcon)
1275 SZ_Clear(&cl_message);
1276 SZ_Write(&cl_message, data, length);
1277 MSG_BeginReading(&cl_message);
1281 SZ_Clear(&sv_message);
1282 SZ_Write(&sv_message, data, length);
1283 MSG_BeginReading(&sv_message);
1289 // Con_DPrint("Got a stale datagram\n");
1292 else if (flags & NETFLAG_ACK)
1294 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1295 if (sequence == (conn->nq.sendSequence - 1))
1297 if (sequence == conn->nq.ackSequence)
1299 conn->nq.ackSequence++;
1300 if (conn->nq.ackSequence != conn->nq.sendSequence)
1301 Con_DPrint("ack sequencing error\n");
1302 conn->lastMessageTime = realtime;
1303 conn->timeout = realtime + newtimeout;
1304 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1306 unsigned int packetLen;
1307 unsigned int dataLen;
1310 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1311 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1313 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1315 dataLen = conn->sendMessageLength;
1320 dataLen = MAX_PACKETFRAGMENT;
1324 packetLen = NET_HEADERSIZE + dataLen;
1326 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
1327 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
1328 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1330 conn->nq.sendSequence++;
1332 sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1333 if (sendme && NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress) == (int)sendmelen)
1335 conn->lastSendTime = realtime;
1336 conn->packetsSent++;
1340 conn->sendMessageLength = 0;
1343 // Con_DPrint("Duplicate ACK received\n");
1346 // Con_DPrint("Stale ACK received\n");
1349 else if (flags & NETFLAG_DATA)
1351 unsigned char temppacket[8];
1352 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes += originallength + 28;
1353 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes += 8 + 28;
1354 StoreBigLong(temppacket, 8 | NETFLAG_ACK);
1355 StoreBigLong(temppacket + 4, sequence);
1356 sendme = Crypto_EncryptPacket(&conn->crypto, temppacket, 8, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1358 NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
1359 if (sequence == conn->nq.receiveSequence)
1361 conn->lastMessageTime = realtime;
1362 conn->timeout = realtime + newtimeout;
1363 conn->nq.receiveSequence++;
1364 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1365 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1366 conn->receiveMessageLength += length;
1368 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1369 "Dropping the message!\n", sequence );
1370 conn->receiveMessageLength = 0;
1373 if (flags & NETFLAG_EOM)
1375 conn->reliableMessagesReceived++;
1376 length = conn->receiveMessageLength;
1377 conn->receiveMessageLength = 0;
1380 if (conn == cls.netcon)
1382 SZ_Clear(&cl_message);
1383 SZ_Write(&cl_message, conn->receiveMessage, length);
1384 MSG_BeginReading(&cl_message);
1388 SZ_Clear(&sv_message);
1389 SZ_Write(&sv_message, conn->receiveMessage, length);
1390 MSG_BeginReading(&sv_message);
1397 conn->receivedDuplicateCount++;
1405 static void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1408 cls.connect_trying = false;
1409 M_Update_Return_Reason("");
1410 // the connection request succeeded, stop current connection and set up a new connection
1412 // if we're connecting to a remote server, shut down any local server
1413 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1415 SV_LockThreadMutex();
1416 Host_ShutdownServer ();
1417 SV_UnlockThreadMutex();
1419 // allocate a net connection to keep track of things
1420 cls.netcon = NetConn_Open(mysocket, peeraddress);
1421 crypto = &cls.crypto;
1422 if(crypto && crypto->authenticated)
1424 Crypto_ServerFinishInstance(&cls.netcon->crypto, crypto);
1425 Con_Printf("%s connection to %s has been established: server is %s@%.*s, I am %.*s@%.*s\n",
1426 crypto->use_aes ? "Encrypted" : "Authenticated",
1427 cls.netcon->address,
1428 crypto->server_idfp[0] ? crypto->server_idfp : "-",
1429 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-",
1430 crypto_keyfp_recommended_length, crypto->client_idfp[0] ? crypto->client_idfp : "-",
1431 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-"
1434 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1435 key_dest = key_game;
1437 cls.demonum = -1; // not in the demo loop now
1438 cls.state = ca_connected;
1439 cls.signon = 0; // need all the signon messages before playing
1440 cls.protocol = initialprotocol;
1441 // reset move sequence numbering on this new connection
1442 cls.servermovesequence = 0;
1443 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1444 Cmd_ForwardStringToServer("new");
1445 if (cls.protocol == PROTOCOL_QUAKE)
1447 // write a keepalive (clc_nop) as it seems to greatly improve the
1448 // chances of connecting to a netquake server
1450 unsigned char buf[4];
1451 memset(&msg, 0, sizeof(msg));
1453 msg.maxsize = sizeof(buf);
1454 MSG_WriteChar(&msg, clc_nop);
1455 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1459 int NetConn_IsLocalGame(void)
1461 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1466 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1470 serverlist_entry_t *entry = NULL;
1472 // search the cache for this server and update it
1473 for (n = 0;n < serverlist_cachecount;n++) {
1474 entry = &serverlist_cache[ n ];
1475 if (!strcmp(addressstring, entry->info.cname))
1479 if (n == serverlist_cachecount)
1481 // LAN search doesnt require an answer from the master server so we wont
1482 // know the ping nor will it be initialized already...
1485 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1488 if (serverlist_maxcachecount <= serverlist_cachecount)
1490 serverlist_maxcachecount += 64;
1491 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1493 entry = &serverlist_cache[n];
1495 memset(entry, 0, sizeof(*entry));
1496 // store the data the engine cares about (address and ping)
1497 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1498 entry->info.ping = 100000;
1499 entry->querytime = realtime;
1500 // if not in the slist menu we should print the server to console
1501 if (serverlist_consoleoutput)
1502 Con_Printf("querying %s\n", addressstring);
1503 ++serverlist_cachecount;
1505 // if this is the first reply from this server, count it as having replied
1506 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1507 pingtime = bound(0, pingtime, 9999);
1508 if (entry->query == SQS_REFRESHING) {
1509 entry->info.ping = pingtime;
1510 entry->query = SQS_QUERIED;
1512 // convert to unsigned to catch the -1
1513 // 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]
1514 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1518 // other server info is updated by the caller
1522 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1524 serverlist_entry_t *entry = &serverlist_cache[n];
1525 serverlist_info_t *info = &entry->info;
1526 // update description strings for engine menu and console output
1527 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);
1528 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1530 info->gameversion != gameversion.integer
1533 gameversion_min.integer >= 0 // min/max range set by user/mod?
1534 && gameversion_max.integer >= 0
1535 && gameversion_min.integer <= info->gameversion // version of server in min/max range?
1536 && gameversion_max.integer >= info->gameversion
1539 info->mod, info->map);
1540 if (entry->query == SQS_QUERIED)
1542 if(!serverlist_paused)
1543 ServerList_ViewList_Remove(entry);
1545 // if not in the slist menu we should print the server to console (if wanted)
1546 else if( serverlist_consoleoutput )
1547 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1548 // and finally, update the view set
1549 if(!serverlist_paused)
1550 ServerList_ViewList_Insert( entry );
1551 // update the entry's state
1552 serverlist_cache[n].query = SQS_QUERIED;
1555 // returns true, if it's sensible to continue the processing
1556 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1558 serverlist_entry_t *entry;
1560 // ignore the rest of the message if the serverlist is full
1561 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1563 // also ignore it if we have already queried it (other master server response)
1564 for( n = 0 ; n < serverlist_cachecount ; n++ )
1565 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1568 if( n < serverlist_cachecount ) {
1569 // the entry has already been queried once or
1573 if (serverlist_maxcachecount <= n)
1575 serverlist_maxcachecount += 64;
1576 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1579 entry = &serverlist_cache[n];
1581 memset(entry, 0, sizeof(entry));
1582 entry->protocol = protocol;
1583 // store the data the engine cares about (address and ping)
1584 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1586 entry->info.isfavorite = isfavorite;
1588 // no, then reset the ping right away
1589 entry->info.ping = -1;
1590 // we also want to increase the serverlist_cachecount then
1591 serverlist_cachecount++;
1594 entry->query = SQS_QUERYING;
1599 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1602 if (serverlist_consoleoutput)
1603 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1606 char ipstring [128];
1609 if (data[0] == '\\')
1611 unsigned short port = data[5] * 256 + data[6];
1613 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1614 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1616 // move on to next address in packet
1621 else if (data[0] == '/' && isextended && length >= 19)
1623 unsigned short port = data[17] * 256 + data[18];
1631 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1633 ifname = LHNETADDRESS_GetInterfaceName(senderaddress, ifnamebuf, sizeof(ifnamebuf));
1636 dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x%%%s]:%hu",
1637 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1638 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1644 dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x]:%hu",
1645 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1646 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1651 // move on to next address in packet
1657 Con_Print("Error while parsing the server list\n");
1661 if (serverlist_consoleoutput && developer_networking.integer)
1662 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1664 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1670 // begin or resume serverlist queries
1671 serverlist_querysleep = false;
1672 serverlist_querywaittime = realtime + 3;
1675 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1677 qboolean fromserver;
1678 int ret, c, control;
1680 char *string, addressstring2[128], ipstring[32];
1681 char stringbuf[16384];
1682 char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1684 char infostringvalue[MAX_INPUTLINE];
1687 // quakeworld ingame packet
1688 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1690 // convert the address to a string incase we need it
1691 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1693 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1695 // received a command string - strip off the packaging and put it
1696 // into our string buffer with NULL termination
1699 length = min(length, (int)sizeof(stringbuf) - 1);
1700 memcpy(stringbuf, data, length);
1701 stringbuf[length] = 0;
1704 if (developer_networking.integer)
1706 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1707 Com_HexDumpToConsole(data, length);
1710 sendlength = sizeof(senddata) - 4;
1711 switch(Crypto_ClientParsePacket(string, length, senddata+4, &sendlength, peeraddress))
1713 case CRYPTO_NOMATCH:
1719 memcpy(senddata, "\377\377\377\377", 4);
1720 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1723 case CRYPTO_DISCARD:
1726 memcpy(senddata, "\377\377\377\377", 4);
1727 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1731 case CRYPTO_REPLACE:
1732 string = senddata+4;
1733 length = sendlength;
1737 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1740 for (j = 0;j < MAX_RCONS;j++)
1742 // note: this value from i is used outside the loop too...
1743 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1744 if(cls.rcon_commands[i][0])
1745 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1754 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1755 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1757 e = strchr(rcon_password.string, ' ');
1758 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1760 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1764 strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1765 NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1766 cls.rcon_commands[i][0] = 0;
1769 for (k = 0;k < MAX_RCONS;k++)
1770 if(cls.rcon_commands[k][0])
1771 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1776 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1777 // extend the timeout on other requests as we asked for a challenge
1778 for (l = 0;l < MAX_RCONS;l++)
1779 if(cls.rcon_commands[l][0])
1780 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1781 cls.rcon_timeout[l] = realtime + rcon_secure_challengetimeout.value;
1784 return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1788 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1790 // darkplaces or quake3
1791 char protocolnames[1400];
1792 Protocol_Names(protocolnames, sizeof(protocolnames));
1793 Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1794 M_Update_Return_Reason("Got challenge response");
1795 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1796 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1797 // TODO: add userinfo stuff here instead of using NQ commands?
1798 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);
1801 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1803 // darkplaces or quake3
1804 M_Update_Return_Reason("Accepted");
1805 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1808 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1810 char rejectreason[128];
1811 cls.connect_trying = false;
1813 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1814 memcpy(rejectreason, string, length);
1815 rejectreason[length] = 0;
1816 M_Update_Return_Reason(rejectreason);
1819 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1821 serverlist_info_t *info;
1826 // search the cache for this server and update it
1827 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1831 info = &serverlist_cache[n].info;
1836 info->qcstatus[0] = 0;
1837 info->players[0] = 0;
1838 info->protocol = -1;
1839 info->numplayers = 0;
1841 info->maxplayers = 0;
1842 info->gameversion = 0;
1844 p = strchr(string, '\n');
1847 *p = 0; // cut off the string there
1851 Con_Printf("statusResponse without players block?\n");
1853 if ((s = InfoString_GetValue(string, "gamename" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->game, s, sizeof (info->game));
1854 if ((s = InfoString_GetValue(string, "modname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1855 if ((s = InfoString_GetValue(string, "mapname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1856 if ((s = InfoString_GetValue(string, "hostname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));
1857 if ((s = InfoString_GetValue(string, "protocol" , infostringvalue, sizeof(infostringvalue))) != NULL) info->protocol = atoi(s);
1858 if ((s = InfoString_GetValue(string, "clients" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numplayers = atoi(s);
1859 if ((s = InfoString_GetValue(string, "bots" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numbots = atoi(s);
1860 if ((s = InfoString_GetValue(string, "sv_maxclients", infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);
1861 if ((s = InfoString_GetValue(string, "gameversion" , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);
1862 if ((s = InfoString_GetValue(string, "qcstatus" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1863 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1864 info->numhumans = info->numplayers - max(0, info->numbots);
1865 info->freeslots = info->maxplayers - info->numplayers;
1867 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1871 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1873 serverlist_info_t *info;
1877 // search the cache for this server and update it
1878 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1882 info = &serverlist_cache[n].info;
1887 info->qcstatus[0] = 0;
1888 info->players[0] = 0;
1889 info->protocol = -1;
1890 info->numplayers = 0;
1892 info->maxplayers = 0;
1893 info->gameversion = 0;
1895 if ((s = InfoString_GetValue(string, "gamename" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->game, s, sizeof (info->game));
1896 if ((s = InfoString_GetValue(string, "modname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1897 if ((s = InfoString_GetValue(string, "mapname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1898 if ((s = InfoString_GetValue(string, "hostname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));
1899 if ((s = InfoString_GetValue(string, "protocol" , infostringvalue, sizeof(infostringvalue))) != NULL) info->protocol = atoi(s);
1900 if ((s = InfoString_GetValue(string, "clients" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numplayers = atoi(s);
1901 if ((s = InfoString_GetValue(string, "bots" , infostringvalue, sizeof(infostringvalue))) != NULL) info->numbots = atoi(s);
1902 if ((s = InfoString_GetValue(string, "sv_maxclients", infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);
1903 if ((s = InfoString_GetValue(string, "gameversion" , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);
1904 if ((s = InfoString_GetValue(string, "qcstatus" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1905 info->numhumans = info->numplayers - max(0, info->numbots);
1906 info->freeslots = info->maxplayers - info->numplayers;
1908 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1912 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1914 // Extract the IP addresses
1917 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1920 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1922 // Extract the IP addresses
1925 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1928 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1930 // Extract the IP addresses
1934 if (serverlist_consoleoutput)
1935 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1936 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1938 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1939 if (serverlist_consoleoutput && developer_networking.integer)
1940 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1942 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1946 // move on to next address in packet
1950 // begin or resume serverlist queries
1951 serverlist_querysleep = false;
1952 serverlist_querywaittime = realtime + 3;
1955 if (!strncmp(string, "extResponse ", 12))
1957 ++cl_net_extresponse_count;
1958 if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1959 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1960 cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1961 dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1964 if (!strncmp(string, "ping", 4))
1966 if (developer_extra.integer)
1967 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1968 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1971 if (!strncmp(string, "ack", 3))
1973 // QuakeWorld compatibility
1974 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1976 // challenge message
1977 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1978 M_Update_Return_Reason("Got QuakeWorld challenge response");
1979 cls.qw_qport = qport.integer;
1980 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1981 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1982 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);
1985 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1988 M_Update_Return_Reason("QuakeWorld Accepted");
1989 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1992 if (length > 2 && !memcmp(string, "n\\", 2))
1994 serverlist_info_t *info;
1998 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1999 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
2002 // search the cache for this server and update it
2003 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2007 info = &serverlist_cache[n].info;
2008 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
2009 if ((s = InfoString_GetValue(string, "*gamedir" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
2010 if ((s = InfoString_GetValue(string, "map" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
2011 if ((s = InfoString_GetValue(string, "hostname" , infostringvalue, sizeof(infostringvalue))) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
2013 info->numplayers = 0; // updated below
2014 info->numhumans = 0; // updated below
2015 if ((s = InfoString_GetValue(string, "maxclients" , infostringvalue, sizeof(infostringvalue))) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
2016 if ((s = InfoString_GetValue(string, "gameversion" , infostringvalue, sizeof(infostringvalue))) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
2018 // count active players on server
2019 // (we could gather more info, but we're just after the number)
2020 s = strchr(string, '\n');
2024 while (s < string + length)
2026 for (;s < string + length && *s != '\n';s++)
2028 if (s >= string + length)
2036 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2040 if (string[0] == 'n')
2043 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
2045 // we may not have liked the packet, but it was a command packet, so
2046 // we're done processing this packet now
2049 // quakeworld ingame packet
2050 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2053 CL_ParseServerMessage();
2056 // netquake control packets, supported for compatibility only
2057 if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length && !ENCRYPTION_REQUIRED)
2060 serverlist_info_t *info;
2064 SZ_Clear(&cl_message);
2065 SZ_Write(&cl_message, data, length);
2066 MSG_BeginReading(&cl_message);
2067 c = MSG_ReadByte(&cl_message);
2071 if (developer_extra.integer)
2072 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
2073 if (cls.connect_trying)
2075 lhnetaddress_t clientportaddress;
2076 clientportaddress = *peeraddress;
2077 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong(&cl_message));
2078 // extra ProQuake stuff
2080 cls.proquake_servermod = MSG_ReadByte(&cl_message); // MOD_PROQUAKE
2082 cls.proquake_servermod = 0;
2084 cls.proquake_serverversion = MSG_ReadByte(&cl_message); // version * 10
2086 cls.proquake_serverversion = 0;
2088 cls.proquake_serverflags = MSG_ReadByte(&cl_message); // flags (mainly PQF_CHEATFREE)
2090 cls.proquake_serverflags = 0;
2091 if (cls.proquake_servermod == 1)
2092 Con_Printf("Connected to ProQuake %.1f server, enabling precise aim\n", cls.proquake_serverversion / 10.0f);
2093 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
2094 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
2095 M_Update_Return_Reason("Accepted");
2096 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
2100 if (developer_extra.integer)
2101 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
2102 cls.connect_trying = false;
2103 M_Update_Return_Reason((char *)MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)));
2105 case CCREP_SERVER_INFO:
2106 if (developer_extra.integer)
2107 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
2108 // LordHavoc: because the quake server may report weird addresses
2109 // we just ignore it and keep the real address
2110 MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
2111 // search the cache for this server and update it
2112 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2116 info = &serverlist_cache[n].info;
2117 strlcpy(info->game, "Quake", sizeof(info->game));
2118 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
2119 strlcpy(info->name, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(info->name));
2120 strlcpy(info->map , MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(info->map));
2121 info->numplayers = MSG_ReadByte(&cl_message);
2122 info->maxplayers = MSG_ReadByte(&cl_message);
2123 info->protocol = MSG_ReadByte(&cl_message);
2125 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2128 case CCREP_RCON: // RocketGuy: ProQuake rcon support
2129 if (developer_extra.integer)
2130 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
2132 Con_Printf("%s\n", MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)));
2134 case CCREP_PLAYER_INFO:
2135 // we got a CCREP_PLAYER_INFO??
2136 //if (developer_extra.integer)
2137 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
2139 case CCREP_RULE_INFO:
2140 // we got a CCREP_RULE_INFO??
2141 //if (developer_extra.integer)
2142 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
2147 SZ_Clear(&cl_message);
2148 // we may not have liked the packet, but it was a valid control
2149 // packet, so we're done processing this packet now
2153 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2154 CL_ParseServerMessage();
2158 void NetConn_QueryQueueFrame(void)
2164 static double querycounter = 0;
2166 if(!net_slist_pause.integer && serverlist_paused)
2167 ServerList_RebuildViewList();
2168 serverlist_paused = net_slist_pause.integer != 0;
2170 if (serverlist_querysleep)
2173 // apply a cool down time after master server replies,
2174 // to avoid messing up the ping times on the servers
2175 if (serverlist_querywaittime > realtime)
2178 // each time querycounter reaches 1.0 issue a query
2179 querycounter += cl.realframetime * net_slist_queriespersecond.value;
2180 maxqueries = (int)querycounter;
2181 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2182 querycounter -= maxqueries;
2184 if( maxqueries == 0 ) {
2188 // scan serverlist and issue queries as needed
2189 serverlist_querysleep = true;
2191 timeouttime = realtime - net_slist_timeout.value;
2192 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
2194 serverlist_entry_t *entry = &serverlist_cache[ index ];
2195 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2200 serverlist_querysleep = false;
2201 if( entry->querycounter != 0 && entry->querytime > timeouttime )
2206 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
2208 lhnetaddress_t address;
2211 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2212 if (entry->protocol == PROTOCOL_QUAKEWORLD)
2214 for (socket = 0; socket < cl_numsockets ; socket++)
2215 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2219 for (socket = 0; socket < cl_numsockets ; socket++)
2220 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2223 // update the entry fields
2224 entry->querytime = realtime;
2225 entry->querycounter++;
2227 // if not in the slist menu we should print the server to console
2228 if (serverlist_consoleoutput)
2229 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2235 // have we tried to refresh this server?
2236 if( entry->query == SQS_REFRESHING ) {
2237 // yes, so update the reply count (since its not responding anymore)
2239 if(!serverlist_paused)
2240 ServerList_ViewList_Remove(entry);
2242 entry->query = SQS_TIMEDOUT;
2247 void NetConn_ClientFrame(void)
2250 lhnetaddress_t peeraddress;
2251 unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
2252 NetConn_UpdateSockets();
2253 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2255 if (cls.connect_remainingtries == 0)
2256 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2257 cls.connect_nextsendtime = realtime + 1;
2258 cls.connect_remainingtries--;
2259 if (cls.connect_remainingtries <= -10)
2261 cls.connect_trying = false;
2262 M_Update_Return_Reason("Connect: Failed");
2265 // try challenge first (newer DP server or QW)
2266 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2267 // then try netquake as a fallback (old server, or netquake)
2268 SZ_Clear(&cl_message);
2269 // save space for the header, filled in later
2270 MSG_WriteLong(&cl_message, 0);
2271 MSG_WriteByte(&cl_message, CCREQ_CONNECT);
2272 MSG_WriteString(&cl_message, "QUAKE");
2273 MSG_WriteByte(&cl_message, NET_PROTOCOL_VERSION);
2274 // extended proquake stuff
2275 MSG_WriteByte(&cl_message, 1); // mod = MOD_PROQUAKE
2276 // this version matches ProQuake 3.40, the first version to support
2277 // the NAT fix, and it only supports the NAT fix for ProQuake 3.40 or
2278 // higher clients, so we pretend we are that version...
2279 MSG_WriteByte(&cl_message, 34); // version * 10
2280 MSG_WriteByte(&cl_message, 0); // flags
2281 MSG_WriteLong(&cl_message, 0); // password
2282 // write the packetsize now...
2283 StoreBigLong(cl_message.data, NETFLAG_CTL | (cl_message.cursize & NETFLAG_LENGTH_MASK));
2284 NetConn_Write(cls.connect_mysocket, cl_message.data, cl_message.cursize, &cls.connect_address);
2285 SZ_Clear(&cl_message);
2287 for (i = 0;i < cl_numsockets;i++)
2289 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2291 // R_TimeReport("clientreadnetwork");
2292 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2293 // R_TimeReport("clientparsepacket");
2296 NetConn_QueryQueueFrame();
2297 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2299 Con_Print("Connection timed out\n");
2301 SV_LockThreadMutex();
2302 Host_ShutdownServer ();
2303 SV_UnlockThreadMutex();
2307 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2311 for (i = 0;i < bufferlength - 1;i++)
2315 c = rand () % (127 - 33) + 33;
2316 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2322 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2323 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2325 prvm_prog_t *prog = SVVM_prog;
2327 unsigned int nb_clients = 0, nb_bots = 0, i;
2330 const char *crypto_idstring;
2333 // How many clients are there?
2334 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2336 if (svs.clients[i].active)
2339 if (!svs.clients[i].netconnection)
2345 str = PRVM_GetString(prog, PRVM_serverglobalstring(worldstatus));
2351 for(q = str; *q && (size_t)(p - qcstatus) < (sizeof(qcstatus) - 1); ++q)
2352 if(*q != '\\' && *q != '\n')
2357 /// \TODO: we should add more information for the full status string
2358 crypto_idstring = Crypto_GetInfoResponseDataString();
2359 length = dpsnprintf(out_msg, out_size,
2360 "\377\377\377\377%s\x0A"
2361 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2362 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2367 fullstatus ? "statusResponse" : "infoResponse",
2368 gamename, com_modname, gameversion.integer, svs.maxclients,
2369 nb_clients, nb_bots, sv.worldbasename, hostname.string, NET_PROTOCOL_VERSION,
2370 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2371 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2372 crypto_idstring ? "\\d0_blind_id\\" : "", crypto_idstring ? crypto_idstring : "",
2373 fullstatus ? "\n" : "");
2375 // Make sure it fits in the buffer
2385 savelength = length;
2387 ptr = out_msg + length;
2388 left = (int)out_size - length;
2390 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2392 client_t *cl = &svs.clients[i];
2395 int nameind, cleanind, pingvalue;
2397 char cleanname [sizeof(cl->name)];
2401 // Remove all characters '"' and '\' in the player name
2406 curchar = cl->name[nameind++];
2407 if (curchar != '"' && curchar != '\\')
2409 cleanname[cleanind++] = curchar;
2410 if (cleanind == sizeof(cleanname) - 1)
2413 } while (curchar != '\0');
2414 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2416 pingvalue = (int)(cl->ping * 1000.0f);
2417 if(cl->netconnection)
2418 pingvalue = bound(1, pingvalue, 9999);
2423 ed = PRVM_EDICT_NUM(i + 1);
2424 str = PRVM_GetString(prog, PRVM_serveredictstring(ed, clientstatus));
2430 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2431 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2436 if ((gamemode == GAME_NEXUIZ || gamemode == GAME_XONOTIC) && (teamplay.integer > 0))
2438 if(cl->frags == -666) // spectator
2439 strlcpy(teambuf, " 0", sizeof(teambuf));
2440 else if(cl->colors == 0x44) // red team
2441 strlcpy(teambuf, " 1", sizeof(teambuf));
2442 else if(cl->colors == 0xDD) // blue team
2443 strlcpy(teambuf, " 2", sizeof(teambuf));
2444 else if(cl->colors == 0xCC) // yellow team
2445 strlcpy(teambuf, " 3", sizeof(teambuf));
2446 else if(cl->colors == 0x99) // pink team
2447 strlcpy(teambuf, " 4", sizeof(teambuf));
2449 strlcpy(teambuf, " 0", sizeof(teambuf));
2454 // note: team number is inserted according to SoF2 protocol
2456 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2462 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2471 // turn it into an infoResponse!
2472 out_msg[savelength] = 0;
2473 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2474 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2489 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2491 int floodslotnum, bestfloodslotnum;
2492 double bestfloodtime;
2493 lhnetaddress_t noportpeeraddress;
2494 // see if this is a connect flood
2495 noportpeeraddress = *peeraddress;
2496 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2497 bestfloodslotnum = 0;
2498 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2499 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2501 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2503 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2504 bestfloodslotnum = floodslotnum;
2506 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2508 // this address matches an ongoing flood address
2509 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2511 // renew the ban on this address so it does not expire
2512 // until the flood has subsided
2513 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2514 //Con_Printf("Flood detected!\n");
2517 // the flood appears to have subsided, so allow this
2518 bestfloodslotnum = floodslotnum; // reuse the same slot
2522 // begin a new timeout on this address
2523 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2524 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2525 //Con_Printf("Flood detection initiated!\n");
2529 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2532 lhnetaddress_t noportpeeraddress;
2533 // see if this is a connect flood
2534 noportpeeraddress = *peeraddress;
2535 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2536 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2538 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2540 // this address matches an ongoing flood address
2542 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2543 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2544 //Con_Printf("Flood cleared!\n");
2549 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2551 static qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2556 t1 = (long) time(NULL);
2557 t2 = strtol(s, NULL, 0);
2558 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2561 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2564 return !memcmp(mdfourbuf, hash, 16);
2567 static qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2572 if(slen < (int)(sizeof(challenge[0].string)) - 1)
2575 // validate the challenge
2576 for (i = 0;i < MAX_CHALLENGES;i++)
2577 if(challenge[i].time > 0)
2578 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2580 // if the challenge is not recognized, drop the packet
2581 if (i == MAX_CHALLENGES)
2584 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2587 if(memcmp(mdfourbuf, hash, 16))
2590 // unmark challenge to prevent replay attacks
2591 challenge[i].time = 0;
2596 static qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2598 return !strcmp(password, hash);
2601 /// returns a string describing the user level, or NULL for auth failure
2602 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)
2604 const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2605 static char buf[MAX_INPUTLINE];
2607 qboolean restricted = false;
2608 qboolean have_usernames = false;
2611 userpass_start = rcon_password.string;
2612 while((userpass_end = strchr(userpass_start, ' ')))
2614 have_usernames = true;
2615 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2617 if(comparator(peeraddress, buf, password, cs, cslen))
2619 userpass_start = userpass_end + 1;
2621 if(userpass_start[0])
2623 userpass_end = userpass_start + strlen(userpass_start);
2624 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2629 have_usernames = false;
2630 userpass_start = rcon_restricted_password.string;
2631 while((userpass_end = strchr(userpass_start, ' ')))
2633 have_usernames = true;
2634 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2636 if(comparator(peeraddress, buf, password, cs, cslen))
2638 userpass_start = userpass_end + 1;
2640 if(userpass_start[0])
2642 userpass_end = userpass_start + strlen(userpass_start);
2643 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2647 return NULL; // DENIED
2650 for(text = s; text != endpos; ++text)
2651 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2652 return NULL; // block possible exploits against the parser/alias expansion
2656 size_t l = strlen(s);
2659 hasquotes = (strchr(s, '"') != NULL);
2660 // sorry, we can't allow these substrings in wildcard expressions,
2661 // as they can mess with the argument counts
2662 text = rcon_restricted_commands.string;
2663 while(COM_ParseToken_Console(&text))
2665 // com_token now contains a pattern to check for...
2666 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2669 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2672 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2674 if(!strcmp(com_token, s))
2677 else // single-arg expression? must match the beginning of the command
2679 if(!strcmp(com_token, s))
2681 if(!memcmp(va(vabuf, sizeof(vabuf), "%s ", com_token), s, strlen(com_token) + 1))
2685 // if we got here, nothing matched!
2693 userpass_startpass = strchr(userpass_start, ':');
2694 if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2695 return va(vabuf, sizeof(vabuf), "%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2697 return va(vabuf, sizeof(vabuf), "%srcon", restricted ? "restricted " : "");
2700 static void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos, qboolean proquakeprotocol)
2704 // looks like a legitimate rcon command with the correct password
2705 const char *s_ptr = s;
2706 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2707 while(s_ptr != endpos)
2709 size_t l = strlen(s_ptr);
2711 Con_Printf(" %s;", s_ptr);
2716 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2717 Con_Rcon_Redirect_Init(mysocket, peeraddress, proquakeprotocol);
2720 size_t l = strlen(s);
2723 client_t *host_client_save = host_client;
2724 Cmd_ExecuteString(s, src_command, true);
2725 host_client = host_client_save;
2726 // in case it is a command that changes host_client (like restart)
2730 Con_Rcon_Redirect_End();
2734 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2738 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2740 int i, ret, clientnum, best;
2743 char *s, *string, response[1400], addressstring2[128];
2744 static char stringbuf[16384]; // server only
2745 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2746 char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
2747 size_t sendlength, response_len;
2748 char infostringvalue[MAX_INPUTLINE];
2754 // convert the address to a string incase we need it
2755 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2757 // see if we can identify the sender as a local player
2758 // (this is necessary for rcon to send a reliable reply if the client is
2759 // actually on the server, not sending remotely)
2760 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2761 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2763 if (i == svs.maxclients)
2766 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2768 // received a command string - strip off the packaging and put it
2769 // into our string buffer with NULL termination
2772 length = min(length, (int)sizeof(stringbuf) - 1);
2773 memcpy(stringbuf, data, length);
2774 stringbuf[length] = 0;
2777 if (developer_extra.integer)
2779 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2780 Com_HexDumpToConsole(data, length);
2783 sendlength = sizeof(senddata) - 4;
2784 switch(Crypto_ServerParsePacket(string, length, senddata+4, &sendlength, peeraddress))
2786 case CRYPTO_NOMATCH:
2792 memcpy(senddata, "\377\377\377\377", 4);
2793 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2796 case CRYPTO_DISCARD:
2799 memcpy(senddata, "\377\377\377\377", 4);
2800 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2804 case CRYPTO_REPLACE:
2805 string = senddata+4;
2806 length = sendlength;
2810 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -3))
2812 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2814 if(challenge[i].time > 0)
2815 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2817 if (besttime > challenge[i].time)
2818 besttime = challenge[best = i].time;
2820 // if we did not find an exact match, choose the oldest and
2821 // update address and string
2822 if (i == MAX_CHALLENGES)
2825 challenge[i].address = *peeraddress;
2826 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2828 challenge[i].time = realtime;
2829 // send the challenge
2830 dpsnprintf(response, sizeof(response), "\377\377\377\377challenge %s", challenge[i].string);
2831 response_len = strlen(response) + 1;
2832 Crypto_ServerAppendToChallenge(string, length, response, &response_len, sizeof(response));
2833 NetConn_Write(mysocket, response, response_len, peeraddress);
2836 if (length > 8 && !memcmp(string, "connect\\", 8))
2838 crypto_t *crypto = Crypto_ServerGetInstance(peeraddress);
2842 if(crypto && crypto->authenticated)
2844 // no need to check challenge
2845 if(crypto_developer.integer)
2847 Con_Printf("%s connection to %s is being established: client is %s@%.*s, I am %.*s@%.*s\n",
2848 crypto->use_aes ? "Encrypted" : "Authenticated",
2850 crypto->client_idfp[0] ? crypto->client_idfp : "-",
2851 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-",
2852 crypto_keyfp_recommended_length, crypto->server_idfp[0] ? crypto->server_idfp : "-",
2853 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-"
2859 if ((s = InfoString_GetValue(string, "challenge", infostringvalue, sizeof(infostringvalue))))
2861 // validate the challenge
2862 for (i = 0;i < MAX_CHALLENGES;i++)
2863 if(challenge[i].time > 0)
2864 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2866 // if the challenge is not recognized, drop the packet
2867 if (i == MAX_CHALLENGES)
2872 if((s = InfoString_GetValue(string, "message", infostringvalue, sizeof(infostringvalue))))
2873 Con_DPrintf("Connecting client %s sent us the message: %s\n", addressstring2, s);
2875 if(!(islocal || sv_public.integer > -2))
2877 if (developer_extra.integer)
2878 Con_Printf("Datagram_ParseConnectionless: sending \"reject %s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
2879 NetConn_WriteString(mysocket, va(vabuf, sizeof(vabuf), "\377\377\377\377reject %s", sv_public_rejectreason.string), peeraddress);
2883 // check engine protocol
2884 if(!(s = InfoString_GetValue(string, "protocol", infostringvalue, sizeof(infostringvalue))) || strcmp(s, "darkplaces 3"))
2886 if (developer_extra.integer)
2887 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2888 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2892 // see if this is a duplicate connection request or a disconnected
2893 // client who is rejoining to the same client slot
2894 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2896 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2898 // this is a known client...
2899 if(crypto && crypto->authenticated)
2901 // reject if changing key!
2902 if(client->netconnection->crypto.authenticated)
2905 strcmp(client->netconnection->crypto.client_idfp, crypto->client_idfp)
2907 strcmp(client->netconnection->crypto.server_idfp, crypto->server_idfp)
2909 strcmp(client->netconnection->crypto.client_keyfp, crypto->client_keyfp)
2911 strcmp(client->netconnection->crypto.server_keyfp, crypto->server_keyfp)
2914 if (developer_extra.integer)
2915 Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to change key of crypto.\" to %s.\n", addressstring2);
2916 NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to change key of crypto.", peeraddress);
2923 // reject if downgrading!
2924 if(client->netconnection->crypto.authenticated)
2926 if (developer_extra.integer)
2927 Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to downgrade crypto.\" to %s.\n", addressstring2);
2928 NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to downgrade crypto.", peeraddress);
2932 if (client->spawned)
2934 // client crashed and is coming back,
2935 // keep their stuff intact
2936 if (developer_extra.integer)
2937 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2938 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2939 if(crypto && crypto->authenticated)
2940 Crypto_ServerFinishInstance(&client->netconnection->crypto, crypto);
2941 SV_SendServerinfo(client);
2945 // client is still trying to connect,
2946 // so we send a duplicate reply
2947 if (developer_extra.integer)
2948 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2949 if(crypto && crypto->authenticated)
2950 Crypto_ServerFinishInstance(&client->netconnection->crypto, crypto);
2951 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2957 if (NetConn_PreventConnectFlood(peeraddress))
2960 // find an empty client slot for this new client
2961 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2964 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2966 // allocated connection
2967 if (developer_extra.integer)
2968 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2969 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2970 // now set up the client
2971 if(crypto && crypto->authenticated)
2972 Crypto_ServerFinishInstance(&conn->crypto, crypto);
2973 SV_ConnectClient(clientnum, conn);
2974 NetConn_Heartbeat(1);
2979 // no empty slots found - server is full
2980 if (developer_extra.integer)
2981 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2982 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2986 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2988 const char *challenge = NULL;
2990 // If there was a challenge in the getinfo message
2991 if (length > 8 && string[7] == ' ')
2992 challenge = string + 8;
2994 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2996 if (developer_extra.integer)
2997 Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
2998 NetConn_WriteString(mysocket, response, peeraddress);
3002 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
3004 const char *challenge = NULL;
3006 // If there was a challenge in the getinfo message
3007 if (length > 10 && string[9] == ' ')
3008 challenge = string + 10;
3010 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
3012 if (developer_extra.integer)
3013 Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
3014 NetConn_WriteString(mysocket, response, peeraddress);
3018 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
3020 char *password = string + 20;
3021 char *timeval = string + 37;
3022 char *s = strchr(timeval, ' ');
3023 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3024 const char *userlevel;
3026 if(rcon_secure.integer > 1)
3030 return true; // invalid packet
3033 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
3034 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3037 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
3039 char *password = string + 25;
3040 char *challenge = string + 42;
3041 char *s = strchr(challenge, ' ');
3042 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3043 const char *userlevel;
3045 return true; // invalid packet
3048 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
3049 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3052 if (length >= 5 && !memcmp(string, "rcon ", 5))
3055 char *s = string + 5;
3056 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3059 if(rcon_secure.integer > 0)
3062 for (i = 0;!ISWHITESPACE(*s);s++)
3063 if (i < (int)sizeof(password) - 1)
3065 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
3068 if (!ISWHITESPACE(password[0]))
3070 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3071 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3075 if (!strncmp(string, "extResponse ", 12))
3077 ++sv_net_extresponse_count;
3078 if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
3079 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
3080 sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
3081 dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
3084 if (!strncmp(string, "ping", 4))
3086 if (developer_extra.integer)
3087 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
3088 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
3091 if (!strncmp(string, "ack", 3))
3093 // we may not have liked the packet, but it was a command packet, so
3094 // we're done processing this packet now
3097 // netquake control packets, supported for compatibility only, and only
3098 // when running game protocols that are normally served via this connection
3100 // (this protects more modern protocols against being used for
3101 // Quake packet flood Denial Of Service attacks)
3102 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)
3106 const char *protocolname;
3109 SZ_Clear(&sv_message);
3110 SZ_Write(&sv_message, data, length);
3111 MSG_BeginReading(&sv_message);
3112 c = MSG_ReadByte(&sv_message);
3116 if (developer_extra.integer)
3117 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
3118 if(!(islocal || sv_public.integer > -2))
3120 if (developer_extra.integer)
3121 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"%s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
3122 SZ_Clear(&sv_message);
3123 // save space for the header, filled in later
3124 MSG_WriteLong(&sv_message, 0);
3125 MSG_WriteByte(&sv_message, CCREP_REJECT);
3126 MSG_WriteString(&sv_message, va(vabuf, sizeof(vabuf), "%s\n", sv_public_rejectreason.string));
3127 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3128 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3129 SZ_Clear(&sv_message);
3133 protocolname = MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring));
3134 protocolnumber = MSG_ReadByte(&sv_message);
3135 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
3137 if (developer_extra.integer)
3138 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
3139 SZ_Clear(&sv_message);
3140 // save space for the header, filled in later
3141 MSG_WriteLong(&sv_message, 0);
3142 MSG_WriteByte(&sv_message, CCREP_REJECT);
3143 MSG_WriteString(&sv_message, "Incompatible version.\n");
3144 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3145 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3146 SZ_Clear(&sv_message);
3150 // see if this connect request comes from a known client
3151 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3153 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
3155 // this is either a duplicate connection request
3156 // or coming back from a timeout
3157 // (if so, keep their stuff intact)
3160 if (developer_extra.integer)
3161 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
3162 SZ_Clear(&sv_message);
3163 // save space for the header, filled in later
3164 MSG_WriteLong(&sv_message, 0);
3165 MSG_WriteByte(&sv_message, CCREP_ACCEPT);
3166 MSG_WriteLong(&sv_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
3167 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3168 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3169 SZ_Clear(&sv_message);
3171 // if client is already spawned, re-send the
3172 // serverinfo message as they'll need it to play
3173 if (client->spawned)
3174 SV_SendServerinfo(client);
3179 // this is a new client, check for connection flood
3180 if (NetConn_PreventConnectFlood(peeraddress))
3183 // find a slot for the new client
3184 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3187 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
3189 // connect to the client
3190 // everything is allocated, just fill in the details
3191 strlcpy (conn->address, addressstring2, sizeof (conn->address));
3192 if (developer_extra.integer)
3193 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
3194 // send back the info about the server connection
3195 SZ_Clear(&sv_message);
3196 // save space for the header, filled in later
3197 MSG_WriteLong(&sv_message, 0);
3198 MSG_WriteByte(&sv_message, CCREP_ACCEPT);
3199 MSG_WriteLong(&sv_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
3200 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3201 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3202 SZ_Clear(&sv_message);
3203 // now set up the client struct
3204 SV_ConnectClient(clientnum, conn);
3205 NetConn_Heartbeat(1);
3210 if (developer_extra.integer)
3211 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
3212 // no room; try to let player know
3213 SZ_Clear(&sv_message);
3214 // save space for the header, filled in later
3215 MSG_WriteLong(&sv_message, 0);
3216 MSG_WriteByte(&sv_message, CCREP_REJECT);
3217 MSG_WriteString(&sv_message, "Server is full.\n");
3218 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3219 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3220 SZ_Clear(&sv_message);
3222 case CCREQ_SERVER_INFO:
3223 if (developer_extra.integer)
3224 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
3225 if(!(islocal || sv_public.integer > -1))
3227 if (sv.active && !strcmp(MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), "QUAKE"))
3230 char myaddressstring[128];
3231 if (developer_extra.integer)
3232 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
3233 SZ_Clear(&sv_message);
3234 // save space for the header, filled in later
3235 MSG_WriteLong(&sv_message, 0);
3236 MSG_WriteByte(&sv_message, CCREP_SERVER_INFO);
3237 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
3238 MSG_WriteString(&sv_message, myaddressstring);
3239 MSG_WriteString(&sv_message, hostname.string);
3240 MSG_WriteString(&sv_message, sv.name);
3241 // How many clients are there?
3242 for (i = 0, numclients = 0;i < svs.maxclients;i++)
3243 if (svs.clients[i].active)
3245 MSG_WriteByte(&sv_message, numclients);
3246 MSG_WriteByte(&sv_message, svs.maxclients);
3247 MSG_WriteByte(&sv_message, NET_PROTOCOL_VERSION);
3248 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3249 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3250 SZ_Clear(&sv_message);
3253 case CCREQ_PLAYER_INFO:
3254 if (developer_extra.integer)
3255 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
3256 if(!(islocal || sv_public.integer > -1))
3260 int playerNumber, activeNumber, clientNumber;
3263 playerNumber = MSG_ReadByte(&sv_message);
3265 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3266 if (client->active && ++activeNumber == playerNumber)
3268 if (clientNumber != svs.maxclients)
3270 SZ_Clear(&sv_message);
3271 // save space for the header, filled in later
3272 MSG_WriteLong(&sv_message, 0);
3273 MSG_WriteByte(&sv_message, CCREP_PLAYER_INFO);
3274 MSG_WriteByte(&sv_message, playerNumber);
3275 MSG_WriteString(&sv_message, client->name);
3276 MSG_WriteLong(&sv_message, client->colors);
3277 MSG_WriteLong(&sv_message, client->frags);
3278 MSG_WriteLong(&sv_message, (int)(realtime - client->connecttime));
3279 if(sv_status_privacy.integer)
3280 MSG_WriteString(&sv_message, client->netconnection ? "hidden" : "botclient");
3282 MSG_WriteString(&sv_message, client->netconnection ? client->netconnection->address : "botclient");
3283 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3284 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3285 SZ_Clear(&sv_message);
3289 case CCREQ_RULE_INFO:
3290 if (developer_extra.integer)
3291 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3292 if(!(islocal || sv_public.integer > -1))
3299 // find the search start location
3300 prevCvarName = MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring));
3301 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3303 // send the response
3304 SZ_Clear(&sv_message);
3305 // save space for the header, filled in later
3306 MSG_WriteLong(&sv_message, 0);
3307 MSG_WriteByte(&sv_message, CCREP_RULE_INFO);
3310 MSG_WriteString(&sv_message, var->name);
3311 MSG_WriteString(&sv_message, var->string);
3313 StoreBigLong(sv_message.data, NETFLAG_CTL | (sv_message.cursize & NETFLAG_LENGTH_MASK));
3314 NetConn_Write(mysocket, sv_message.data, sv_message.cursize, peeraddress);
3315 SZ_Clear(&sv_message);
3319 if (developer_extra.integer)
3320 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RCON from %s.\n", addressstring2);
3321 if (sv.active && !rcon_secure.integer)
3323 char password[2048];
3327 const char *userlevel;
3328 strlcpy(password, MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), sizeof(password));
3329 strlcpy(cmd, MSG_ReadString(&sv_message, sv_readstring, sizeof(sv_readstring)), sizeof(cmd));
3331 endpos = cmd + strlen(cmd) + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3332 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3333 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, true);
3340 SZ_Clear(&sv_message);
3341 // we may not have liked the packet, but it was a valid control
3342 // packet, so we're done processing this packet now
3347 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3349 SV_ReadClientMessage();
3356 void NetConn_ServerFrame(void)
3359 lhnetaddress_t peeraddress;
3360 unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
3361 for (i = 0;i < sv_numsockets;i++)
3362 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3363 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3364 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3366 // never timeout loopback connections
3367 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3369 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3370 SV_DropClient(false);
3375 void NetConn_SleepMicroseconds(int microseconds)
3377 LHNET_SleepUntilPacket_Microseconds(microseconds);
3380 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3384 lhnetaddress_t masteraddress;
3385 lhnetaddress_t broadcastaddress;
3388 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3391 // 26000 is the default quake server port, servers on other ports will not
3393 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3394 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3398 for (i = 0;i < cl_numsockets;i++)
3402 const char *cmdname, *extraoptions;
3403 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3405 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3407 // search LAN for Quake servers
3408 SZ_Clear(&cl_message);
3409 // save space for the header, filled in later
3410 MSG_WriteLong(&cl_message, 0);
3411 MSG_WriteByte(&cl_message, CCREQ_SERVER_INFO);
3412 MSG_WriteString(&cl_message, "QUAKE");
3413 MSG_WriteByte(&cl_message, NET_PROTOCOL_VERSION);
3414 StoreBigLong(cl_message.data, NETFLAG_CTL | (cl_message.cursize & NETFLAG_LENGTH_MASK));
3415 NetConn_Write(cl_sockets[i], cl_message.data, cl_message.cursize, &broadcastaddress);
3416 SZ_Clear(&cl_message);
3418 // search LAN for DarkPlaces servers
3419 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3422 // build the getservers message to send to the dpmaster master servers
3423 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3425 cmdname = "getserversExt";
3426 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
3430 cmdname = "getservers";
3433 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3436 for (masternum = 0;sv_masters[masternum].name;masternum++)
3438 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3441 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3445 // search favorite servers
3446 for(j = 0; j < nFavorites; ++j)
3448 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3450 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3451 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3458 // only query QuakeWorld servers when the user wants to
3461 for (i = 0;i < cl_numsockets;i++)
3465 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3467 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3469 // search LAN for QuakeWorld servers
3470 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3472 // build the getservers message to send to the qwmaster master servers
3473 // note this has no -1 prefix, and the trailing nul byte is sent
3474 dpsnprintf(request, sizeof(request), "c\n");
3478 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3480 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3482 if (m_state != m_slist)
3484 char lookupstring[128];
3485 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3486 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3489 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3493 // search favorite servers
3494 for(j = 0; j < nFavorites; ++j)
3496 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3498 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3500 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3501 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3508 if (!masterquerycount)
3510 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3511 M_Update_Return_Reason("No network");
3515 void NetConn_Heartbeat(int priority)
3517 lhnetaddress_t masteraddress;
3519 lhnetsocket_t *mysocket;
3521 // if it's a state change (client connected), limit next heartbeat to no
3522 // more than 30 sec in the future
3523 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3524 nextheartbeattime = realtime + 30.0;
3526 // limit heartbeatperiod to 30 to 270 second range,
3527 // lower limit is to avoid abusing master servers with excess traffic,
3528 // upper limit is to avoid timing out on the master server (which uses
3530 if (sv_heartbeatperiod.value < 30)
3531 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3532 if (sv_heartbeatperiod.value > 270)
3533 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3535 // make advertising optional and don't advertise singleplayer games, and
3536 // only send a heartbeat as often as the admin wants
3537 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3539 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3540 for (masternum = 0;sv_masters[masternum].name;masternum++)
3541 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3542 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3546 static void Net_Heartbeat_f(void)
3549 NetConn_Heartbeat(2);
3551 Con_Print("No server running, can not heartbeat to master server.\n");
3554 static void PrintStats(netconn_t *conn)
3556 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3557 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3559 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3560 Con_Printf("unreliable messages sent = %i\n", conn->unreliableMessagesSent);
3561 Con_Printf("unreliable messages recv = %i\n", conn->unreliableMessagesReceived);
3562 Con_Printf("reliable messages sent = %i\n", conn->reliableMessagesSent);
3563 Con_Printf("reliable messages received = %i\n", conn->reliableMessagesReceived);
3564 Con_Printf("packetsSent = %i\n", conn->packetsSent);
3565 Con_Printf("packetsReSent = %i\n", conn->packetsReSent);
3566 Con_Printf("packetsReceived = %i\n", conn->packetsReceived);
3567 Con_Printf("receivedDuplicateCount = %i\n", conn->receivedDuplicateCount);
3568 Con_Printf("droppedDatagrams = %i\n", conn->droppedDatagrams);
3571 void Net_Stats_f(void)
3574 Con_Print("connections =\n");
3575 for (conn = netconn_list;conn;conn = conn->next)
3579 void Net_Refresh_f(void)
3581 if (m_state != m_slist) {
3582 Con_Print("Sending new requests to master servers\n");
3583 ServerList_QueryList(false, true, false, true);
3584 Con_Print("Listening for replies...\n");
3586 ServerList_QueryList(false, true, false, false);
3589 void Net_Slist_f(void)
3591 ServerList_ResetMasks();
3592 serverlist_sortbyfield = SLIF_PING;
3593 serverlist_sortflags = 0;
3594 if (m_state != m_slist) {
3595 Con_Print("Sending requests to master servers\n");
3596 ServerList_QueryList(true, true, false, true);
3597 Con_Print("Listening for replies...\n");
3599 ServerList_QueryList(true, true, false, false);
3602 void Net_SlistQW_f(void)
3604 ServerList_ResetMasks();
3605 serverlist_sortbyfield = SLIF_PING;
3606 serverlist_sortflags = 0;
3607 if (m_state != m_slist) {
3608 Con_Print("Sending requests to master servers\n");
3609 ServerList_QueryList(true, false, true, true);
3610 serverlist_consoleoutput = true;
3611 Con_Print("Listening for replies...\n");
3613 ServerList_QueryList(true, false, true, false);
3616 void NetConn_Init(void)
3619 lhnetaddress_t tempaddress;
3620 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3621 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3622 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3623 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3624 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3625 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3626 Cvar_RegisterVariable(&rcon_restricted_password);
3627 Cvar_RegisterVariable(&rcon_restricted_commands);
3628 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3629 Cvar_RegisterVariable(&net_slist_queriespersecond);
3630 Cvar_RegisterVariable(&net_slist_queriesperframe);
3631 Cvar_RegisterVariable(&net_slist_timeout);
3632 Cvar_RegisterVariable(&net_slist_maxtries);
3633 Cvar_RegisterVariable(&net_slist_favorites);
3634 Cvar_RegisterVariable(&net_slist_pause);
3635 Cvar_RegisterVariable(&net_messagetimeout);
3636 Cvar_RegisterVariable(&net_connecttimeout);
3637 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3638 Cvar_RegisterVariable(&cl_netlocalping);
3639 Cvar_RegisterVariable(&cl_netpacketloss_send);
3640 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3641 Cvar_RegisterVariable(&hostname);
3642 Cvar_RegisterVariable(&developer_networking);
3643 Cvar_RegisterVariable(&cl_netport);
3644 Cvar_RegisterVariable(&sv_netport);
3645 Cvar_RegisterVariable(&net_address);
3646 Cvar_RegisterVariable(&net_address_ipv6);
3647 Cvar_RegisterVariable(&sv_public);
3648 Cvar_RegisterVariable(&sv_public_rejectreason);
3649 Cvar_RegisterVariable(&sv_heartbeatperiod);
3650 for (i = 0;sv_masters[i].name;i++)
3651 Cvar_RegisterVariable(&sv_masters[i]);
3652 Cvar_RegisterVariable(&gameversion);
3653 Cvar_RegisterVariable(&gameversion_min);
3654 Cvar_RegisterVariable(&gameversion_max);
3655 // 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.
3656 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3658 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3660 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3661 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3664 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3666 // 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
3667 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3669 i = atoi(com_argv[i + 1]);
3670 if (i >= 0 && i < 65536)
3672 Con_Printf("-port option used, setting port cvar to %i\n", i);
3673 Cvar_SetValueQuick(&sv_netport, i);
3676 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3680 cl_message.data = cl_message_buf;
3681 cl_message.maxsize = sizeof(cl_message_buf);
3682 cl_message.cursize = 0;
3683 sv_message.data = sv_message_buf;
3684 sv_message.maxsize = sizeof(sv_message_buf);
3685 sv_message.cursize = 0;
3687 if (Thread_HasThreads())
3688 netconn_mutex = Thread_CreateMutex();
3691 void NetConn_Shutdown(void)
3693 NetConn_CloseClientPorts();
3694 NetConn_CloseServerPorts();
3697 Thread_DestroyMutex(netconn_mutex);
3698 netconn_mutex = NULL;