2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 // for secure rcon authentication
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
34 // note this defaults on for dedicated servers, off for listen servers
35 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect; -3: already block at getchallenge level"};
36 cvar_t sv_public_rejectreason = {0, "sv_public_rejectreason", "The server is closing.", "Rejection reason for connects when sv_public is -2"};
37 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
38 extern cvar_t sv_status_privacy;
40 static cvar_t sv_masters [] =
42 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
43 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
44 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
45 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
46 {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
47 {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
48 {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
50 {0, "sv_masterextra4", "[2001:41d0:2:1628::4450]:27950", "dpmaster.div0.qc.to - default master server 4 (admin: divVerent)"}, // admin: divVerent
55 static cvar_t sv_qwmasters [] =
57 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
58 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
59 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
60 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
61 {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
62 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
63 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
64 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
65 {0, "sv_qwmasterextra5", "qwmaster.fodquake.net:27000", "Global master server. (admin: unknown)"},
69 static double nextheartbeattime = 0;
71 sizebuf_t net_message;
72 static unsigned char net_message_buf[NET_MAXMESSAGE];
74 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
75 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."};
76 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)"};
77 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
78 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
80 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)"};
81 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)"};
82 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)"};
83 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
84 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)"};
85 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
86 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"};
87 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)"};
88 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"};
89 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
90 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"};
91 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"};
92 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"};
93 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
94 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)"};
95 extern cvar_t rcon_secure;
96 extern cvar_t rcon_secure_challengetimeout;
98 /* statistic counters */
99 static int packetsSent = 0;
100 static int packetsReSent = 0;
101 static int packetsReceived = 0;
102 static int receivedDuplicateCount = 0;
103 static int droppedDatagrams = 0;
105 static int unreliableMessagesSent = 0;
106 static int unreliableMessagesReceived = 0;
107 static int reliableMessagesSent = 0;
108 static int reliableMessagesReceived = 0;
110 double masterquerytime = -1000;
111 int masterquerycount = 0;
112 int masterreplycount = 0;
113 int serverquerycount = 0;
114 int serverreplycount = 0;
116 challenge_t challenge[MAX_CHALLENGES];
118 /// this is only false if there are still servers left to query
119 static qboolean serverlist_querysleep = true;
120 static qboolean serverlist_paused = false;
121 /// this is pushed a second or two ahead of realtime whenever a master server
122 /// reply is received, to avoid issuing queries while master replies are still
123 /// flooding in (which would make a mess of the ping times)
124 static double serverlist_querywaittime = 0;
126 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
127 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
128 static unsigned char cryptosendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
129 static unsigned char cryptoreadbuffer[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
131 static int cl_numsockets;
132 static lhnetsocket_t *cl_sockets[16];
133 static int sv_numsockets;
134 static lhnetsocket_t *sv_sockets[16];
136 netconn_t *netconn_list = NULL;
137 mempool_t *netconn_mempool = NULL;
139 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
140 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
141 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
142 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
144 char cl_net_extresponse[NET_EXTRESPONSE_MAX][1400];
145 int cl_net_extresponse_count = 0;
146 int cl_net_extresponse_last = 0;
148 char sv_net_extresponse[NET_EXTRESPONSE_MAX][1400];
149 int sv_net_extresponse_count = 0;
150 int sv_net_extresponse_last = 0;
152 // ServerList interface
153 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
154 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
156 serverlist_infofield_t serverlist_sortbyfield;
157 int serverlist_sortflags;
159 int serverlist_viewcount = 0;
160 unsigned short serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
162 int serverlist_maxcachecount = 0;
163 int serverlist_cachecount = 0;
164 serverlist_entry_t *serverlist_cache = NULL;
166 qboolean serverlist_consoleoutput;
168 static int nFavorites = 0;
169 static lhnetaddress_t favorites[MAX_FAVORITESERVERS];
170 static int nFavorites_idfp = 0;
171 static char favorites_idfp[MAX_FAVORITESERVERS][FP64_SIZE+1];
173 void NetConn_UpdateFavorites(void)
178 p = net_slist_favorites.string;
179 while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
181 if(com_token[0] != '[' && strlen(com_token) == FP64_SIZE && !strchr(com_token, '.'))
182 // currently 44 bytes, longest possible IPv6 address: 39 bytes, so this works
183 // (if v6 address contains port, it must start with '[')
185 strlcpy(favorites_idfp[nFavorites_idfp], com_token, sizeof(favorites_idfp[nFavorites_idfp]));
190 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
196 /// helper function to insert a value into the viewset
197 /// spare entries will be removed
198 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
201 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
202 i = serverlist_viewcount++;
204 i = SERVERLIST_VIEWLISTSIZE - 1;
207 for( ; i > index ; i-- )
208 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
210 serverlist_viewlist[index] = (int)(entry - serverlist_cache);
213 /// we suppose serverlist_viewcount to be valid, ie > 0
214 static void _ServerList_ViewList_Helper_Remove( int index )
216 serverlist_viewcount--;
217 for( ; index < serverlist_viewcount ; index++ )
218 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
221 /// \returns true if A should be inserted before B
222 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
224 int result = 0; // > 0 if for numbers A > B and for text if A < B
226 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
228 if(A->info.isfavorite != B->info.isfavorite)
229 return A->info.isfavorite;
232 switch( serverlist_sortbyfield ) {
234 result = A->info.ping - B->info.ping;
236 case SLIF_MAXPLAYERS:
237 result = A->info.maxplayers - B->info.maxplayers;
239 case SLIF_NUMPLAYERS:
240 result = A->info.numplayers - B->info.numplayers;
243 result = A->info.numbots - B->info.numbots;
246 result = A->info.numhumans - B->info.numhumans;
249 result = A->info.freeslots - B->info.freeslots;
252 result = A->info.protocol - B->info.protocol;
255 result = strcmp( B->info.cname, A->info.cname );
258 result = strcasecmp( B->info.game, A->info.game );
261 result = strcasecmp( B->info.map, A->info.map );
264 result = strcasecmp( B->info.mod, A->info.mod );
267 result = strcasecmp( B->info.name, A->info.name );
270 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
272 case SLIF_ISFAVORITE:
273 result = !!B->info.isfavorite - !!A->info.isfavorite;
276 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
282 if( serverlist_sortflags & SLSF_DESCENDING )
288 // if the chosen sort key is identical, sort by index
289 // (makes this a stable sort, so that later replies from servers won't
290 // shuffle the servers around when they have the same ping)
294 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
296 // This should actually be done with some intermediate and end-of-function return
308 case SLMO_GREATEREQUAL:
310 case SLMO_NOTCONTAIN:
311 case SLMO_STARTSWITH:
312 case SLMO_NOTSTARTSWITH:
315 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
320 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
323 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
324 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
325 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
326 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
328 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
329 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
332 // Same here, also using an intermediate & final return would be more appropriate
336 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
337 case SLMO_NOTCONTAIN:
338 return !*bufferB || !strstr( bufferA, bufferB );
339 case SLMO_STARTSWITH:
340 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
341 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
342 case SLMO_NOTSTARTSWITH:
343 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
345 return strcmp( bufferA, bufferB ) < 0;
347 return strcmp( bufferA, bufferB ) <= 0;
349 return strcmp( bufferA, bufferB ) == 0;
351 return strcmp( bufferA, bufferB ) > 0;
353 return strcmp( bufferA, bufferB ) != 0;
354 case SLMO_GREATEREQUAL:
355 return strcmp( bufferA, bufferB ) >= 0;
357 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
362 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
364 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
366 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
368 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
370 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
372 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
374 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
376 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
378 if( *mask->info.cname
379 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
382 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
385 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
388 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
391 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
393 if( *mask->info.qcstatus
394 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
396 if( *mask->info.players
397 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
399 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
404 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
406 int start, end, mid, i;
409 // reject incompatible servers
411 entry->info.gameversion != gameversion.integer
414 gameversion_min.integer >= 0 // min/max range set by user/mod?
415 && gameversion_max.integer >= 0
416 && gameversion_min.integer >= entry->info.gameversion // version of server in min/max range?
417 && gameversion_max.integer <= entry->info.gameversion
422 // refresh the "favorite" status
423 entry->info.isfavorite = false;
424 if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
426 char idfp[FP64_SIZE+1];
427 for(i = 0; i < nFavorites; ++i)
429 if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
431 entry->info.isfavorite = true;
435 if(Crypto_RetrieveHostKey(&addr, 0, NULL, 0, idfp, sizeof(idfp), NULL))
437 for(i = 0; i < nFavorites_idfp; ++i)
439 if(!strcmp(idfp, favorites_idfp[i]))
441 entry->info.isfavorite = true;
448 // FIXME: change this to be more readable (...)
449 // now check whether it passes through the masks
450 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
451 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
454 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
455 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
457 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
460 if( !serverlist_viewcount ) {
461 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
464 // ok, insert it, we just need to find out where exactly:
467 // check whether to insert it as new first item
468 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(0) ) ) {
469 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
471 } // check whether to insert it as new last item
472 else if( !_ServerList_Entry_Compare( entry, ServerList_GetViewEntry(serverlist_viewcount - 1) ) ) {
473 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
477 end = serverlist_viewcount - 1;
478 while( end > start + 1 )
480 mid = (start + end) / 2;
481 // test the item that lies in the middle between start and end
482 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(mid) ) )
483 // the item has to be in the upper half
486 // the item has to be in the lower half
489 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
492 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
495 for( i = 0; i < serverlist_viewcount; i++ )
497 if (ServerList_GetViewEntry(i) == entry)
499 _ServerList_ViewList_Helper_Remove(i);
505 void ServerList_RebuildViewList(void)
509 serverlist_viewcount = 0;
510 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
511 serverlist_entry_t *entry = &serverlist_cache[i];
512 // also display entries that are currently being refreshed [11/8/2007 Black]
513 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
514 ServerList_ViewList_Insert( entry );
518 void ServerList_ResetMasks(void)
522 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
523 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
524 // numbots needs to be compared to -1 to always succeed
525 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
526 serverlist_andmasks[i].info.numbots = -1;
527 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
528 serverlist_ormasks[i].info.numbots = -1;
531 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
534 int numplayers = 0, maxplayers = 0;
535 for (i = 0;i < serverlist_cachecount;i++)
537 if (serverlist_cache[i].query == SQS_QUERIED)
539 numplayers += serverlist_cache[i].info.numhumans;
540 maxplayers += serverlist_cache[i].info.maxplayers;
543 *numplayerspointer = numplayers;
544 *maxplayerspointer = maxplayers;
548 static void _ServerList_Test(void)
551 if (serverlist_maxcachecount <= 1024)
553 serverlist_maxcachecount = 1024;
554 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
556 for( i = 0 ; i < 1024 ; i++ ) {
557 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
558 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
559 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
560 serverlist_cache[serverlist_cachecount].finished = true;
561 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 );
562 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
563 serverlist_cachecount++;
568 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
570 masterquerytime = realtime;
571 masterquerycount = 0;
572 masterreplycount = 0;
574 serverquerycount = 0;
575 serverreplycount = 0;
576 serverlist_cachecount = 0;
577 serverlist_viewcount = 0;
578 serverlist_maxcachecount = 0;
579 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
581 // refresh all entries
583 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
584 serverlist_entry_t *entry = &serverlist_cache[ n ];
585 entry->query = SQS_REFRESHING;
586 entry->querycounter = 0;
589 serverlist_consoleoutput = consoleoutput;
591 //_ServerList_Test();
593 NetConn_QueryMasters(querydp, queryqw);
598 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
600 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
604 if (cl_netpacketloss_receive.integer)
605 for (i = 0;i < cl_numsockets;i++)
606 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
608 if (developer_networking.integer)
610 char addressstring[128], addressstring2[128];
611 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
614 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
615 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
616 Com_HexDumpToConsole((unsigned char *)data, length);
619 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
624 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
628 if (cl_netpacketloss_send.integer)
629 for (i = 0;i < cl_numsockets;i++)
630 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
632 ret = LHNET_Write(mysocket, data, length, peeraddress);
633 if (developer_networking.integer)
635 char addressstring[128], addressstring2[128];
636 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
637 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
638 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)");
639 Com_HexDumpToConsole((unsigned char *)data, length);
644 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
646 // note this does not include the trailing NULL because we add that in the parser
647 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
650 qboolean NetConn_CanSend(netconn_t *conn)
652 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
653 conn->outgoing_netgraph[conn->outgoing_packetcounter].time = realtime;
654 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
655 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
656 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes = NETGRAPH_NOPACKET;
657 if (realtime > conn->cleartime)
661 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_CHOKEDPACKET;
666 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
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 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;
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 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 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 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 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;
1133 if (protocol == PROTOCOL_QUAKEWORLD)
1135 int sequence, sequence_ack;
1136 int reliable_ack, reliable_message;
1140 sequence = LittleLong(*((int *)(data + 0)));
1141 sequence_ack = LittleLong(*((int *)(data + 4)));
1145 if (conn != cls.netcon)
1150 // 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?)
1151 //qport = LittleShort(*((int *)(data + 8)));
1157 reliable_message = (sequence >> 31) & 1;
1158 reliable_ack = (sequence_ack >> 31) & 1;
1159 sequence &= ~(1<<31);
1160 sequence_ack &= ~(1<<31);
1161 if (sequence <= conn->qw.incoming_sequence)
1163 //Con_DPrint("Got a stale datagram\n");
1166 count = sequence - (conn->qw.incoming_sequence + 1);
1169 droppedDatagrams += count;
1170 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1173 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1174 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1175 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1176 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1177 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1180 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1181 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1182 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1183 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1184 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1185 if (reliable_ack == conn->qw.reliable_sequence)
1187 // received, now we will be able to send another reliable message
1188 conn->sendMessageLength = 0;
1189 reliableMessagesReceived++;
1191 conn->qw.incoming_sequence = sequence;
1192 if (conn == cls.netcon)
1193 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1194 conn->qw.incoming_acknowledged = sequence_ack;
1195 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1196 if (reliable_message)
1197 conn->qw.incoming_reliable_sequence ^= 1;
1198 conn->lastMessageTime = realtime;
1199 conn->timeout = realtime + newtimeout;
1200 unreliableMessagesReceived++;
1201 SZ_Clear(&net_message);
1202 SZ_Write(&net_message, data, length);
1210 unsigned int sequence;
1215 originallength = length;
1216 data = (const unsigned char *) Crypto_DecryptPacket(&conn->crypto, data, length, cryptoreadbuffer, &length, sizeof(cryptoreadbuffer));
1222 qlength = (unsigned int)BuffBigLong(data);
1223 flags = qlength & ~NETFLAG_LENGTH_MASK;
1224 qlength &= NETFLAG_LENGTH_MASK;
1225 // control packets were already handled
1226 if (!(flags & NETFLAG_CTL) && qlength == length)
1228 sequence = BuffBigLong(data + 4);
1232 if (flags & NETFLAG_UNRELIABLE)
1234 if (sequence >= conn->nq.unreliableReceiveSequence)
1236 if (sequence > conn->nq.unreliableReceiveSequence)
1238 count = sequence - conn->nq.unreliableReceiveSequence;
1239 droppedDatagrams += count;
1240 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1243 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1244 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1245 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1246 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1247 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1250 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1251 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1252 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1253 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1254 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1255 conn->nq.unreliableReceiveSequence = sequence + 1;
1256 conn->lastMessageTime = realtime;
1257 conn->timeout = realtime + newtimeout;
1258 unreliableMessagesReceived++;
1261 SZ_Clear(&net_message);
1262 SZ_Write(&net_message, data, length);
1268 // Con_DPrint("Got a stale datagram\n");
1271 else if (flags & NETFLAG_ACK)
1273 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1274 if (sequence == (conn->nq.sendSequence - 1))
1276 if (sequence == conn->nq.ackSequence)
1278 conn->nq.ackSequence++;
1279 if (conn->nq.ackSequence != conn->nq.sendSequence)
1280 Con_DPrint("ack sequencing error\n");
1281 conn->lastMessageTime = realtime;
1282 conn->timeout = realtime + newtimeout;
1283 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1285 unsigned int packetLen;
1286 unsigned int dataLen;
1289 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1290 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1292 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1294 dataLen = conn->sendMessageLength;
1299 dataLen = MAX_PACKETFRAGMENT;
1303 packetLen = NET_HEADERSIZE + dataLen;
1305 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
1306 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
1307 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1309 conn->nq.sendSequence++;
1311 sendme = Crypto_EncryptPacket(&conn->crypto, &sendbuffer, packetLen, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1312 if (sendme && NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress) == (int)sendmelen)
1314 conn->lastSendTime = realtime;
1319 conn->sendMessageLength = 0;
1322 // Con_DPrint("Duplicate ACK received\n");
1325 // Con_DPrint("Stale ACK received\n");
1328 else if (flags & NETFLAG_DATA)
1330 unsigned char temppacket[8];
1331 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes += originallength + 28;
1332 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes += 8 + 28;
1333 StoreBigLong(temppacket, 8 | NETFLAG_ACK);
1334 StoreBigLong(temppacket + 4, sequence);
1335 sendme = Crypto_EncryptPacket(&conn->crypto, temppacket, 8, &cryptosendbuffer, &sendmelen, sizeof(cryptosendbuffer));
1337 NetConn_Write(conn->mysocket, sendme, sendmelen, &conn->peeraddress);
1338 if (sequence == conn->nq.receiveSequence)
1340 conn->lastMessageTime = realtime;
1341 conn->timeout = realtime + newtimeout;
1342 conn->nq.receiveSequence++;
1343 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1344 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1345 conn->receiveMessageLength += length;
1347 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1348 "Dropping the message!\n", sequence );
1349 conn->receiveMessageLength = 0;
1352 if (flags & NETFLAG_EOM)
1354 reliableMessagesReceived++;
1355 length = conn->receiveMessageLength;
1356 conn->receiveMessageLength = 0;
1359 SZ_Clear(&net_message);
1360 SZ_Write(&net_message, conn->receiveMessage, length);
1367 receivedDuplicateCount++;
1375 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1378 cls.connect_trying = false;
1379 M_Update_Return_Reason("");
1380 // the connection request succeeded, stop current connection and set up a new connection
1382 // if we're connecting to a remote server, shut down any local server
1383 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1384 Host_ShutdownServer ();
1385 // allocate a net connection to keep track of things
1386 cls.netcon = NetConn_Open(mysocket, peeraddress);
1387 crypto = &cls.crypto;
1388 if(crypto && crypto->authenticated)
1390 Crypto_ServerFinishInstance(&cls.netcon->crypto, crypto);
1391 Con_Printf("%s connection to %s has been established: server is %s@%.*s, I am %.*s@%.*s\n",
1392 crypto->use_aes ? "Encrypted" : "Authenticated",
1393 cls.netcon->address,
1394 crypto->server_idfp[0] ? crypto->server_idfp : "-",
1395 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-",
1396 crypto_keyfp_recommended_length, crypto->client_idfp[0] ? crypto->client_idfp : "-",
1397 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-"
1400 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1401 key_dest = key_game;
1403 cls.demonum = -1; // not in the demo loop now
1404 cls.state = ca_connected;
1405 cls.signon = 0; // need all the signon messages before playing
1406 cls.protocol = initialprotocol;
1407 // reset move sequence numbering on this new connection
1408 cls.servermovesequence = 0;
1409 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1410 Cmd_ForwardStringToServer("new");
1411 if (cls.protocol == PROTOCOL_QUAKE)
1413 // write a keepalive (clc_nop) as it seems to greatly improve the
1414 // chances of connecting to a netquake server
1416 unsigned char buf[4];
1417 memset(&msg, 0, sizeof(msg));
1419 msg.maxsize = sizeof(buf);
1420 MSG_WriteChar(&msg, clc_nop);
1421 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1425 int NetConn_IsLocalGame(void)
1427 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1432 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1436 serverlist_entry_t *entry = NULL;
1438 // search the cache for this server and update it
1439 for (n = 0;n < serverlist_cachecount;n++) {
1440 entry = &serverlist_cache[ n ];
1441 if (!strcmp(addressstring, entry->info.cname))
1445 if (n == serverlist_cachecount)
1447 // LAN search doesnt require an answer from the master server so we wont
1448 // know the ping nor will it be initialized already...
1451 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1454 if (serverlist_maxcachecount <= serverlist_cachecount)
1456 serverlist_maxcachecount += 64;
1457 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1459 entry = &serverlist_cache[n];
1461 memset(entry, 0, sizeof(*entry));
1462 // store the data the engine cares about (address and ping)
1463 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1464 entry->info.ping = 100000;
1465 entry->querytime = realtime;
1466 // if not in the slist menu we should print the server to console
1467 if (serverlist_consoleoutput)
1468 Con_Printf("querying %s\n", addressstring);
1469 ++serverlist_cachecount;
1471 // if this is the first reply from this server, count it as having replied
1472 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1473 pingtime = bound(0, pingtime, 9999);
1474 if (entry->query == SQS_REFRESHING) {
1475 entry->info.ping = pingtime;
1476 entry->query = SQS_QUERIED;
1478 // convert to unsigned to catch the -1
1479 // 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]
1480 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1484 // other server info is updated by the caller
1488 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1490 serverlist_entry_t *entry = &serverlist_cache[n];
1491 serverlist_info_t *info = &entry->info;
1492 // update description strings for engine menu and console output
1493 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);
1494 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1496 info->gameversion != gameversion.integer
1499 gameversion_min.integer >= 0 // min/max range set by user/mod?
1500 && gameversion_max.integer >= 0
1501 && gameversion_min.integer >= info->gameversion // version of server in min/max range?
1502 && gameversion_max.integer <= info->gameversion
1505 info->mod, info->map);
1506 if (entry->query == SQS_QUERIED)
1508 if(!serverlist_paused)
1509 ServerList_ViewList_Remove(entry);
1511 // if not in the slist menu we should print the server to console (if wanted)
1512 else if( serverlist_consoleoutput )
1513 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1514 // and finally, update the view set
1515 if(!serverlist_paused)
1516 ServerList_ViewList_Insert( entry );
1517 // update the entry's state
1518 serverlist_cache[n].query = SQS_QUERIED;
1521 // returns true, if it's sensible to continue the processing
1522 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1524 serverlist_entry_t *entry;
1526 // ignore the rest of the message if the serverlist is full
1527 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1529 // also ignore it if we have already queried it (other master server response)
1530 for( n = 0 ; n < serverlist_cachecount ; n++ )
1531 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1534 if( n < serverlist_cachecount ) {
1535 // the entry has already been queried once or
1539 if (serverlist_maxcachecount <= n)
1541 serverlist_maxcachecount += 64;
1542 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1545 entry = &serverlist_cache[n];
1547 memset(entry, 0, sizeof(entry));
1548 entry->protocol = protocol;
1549 // store the data the engine cares about (address and ping)
1550 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1552 entry->info.isfavorite = isfavorite;
1554 // no, then reset the ping right away
1555 entry->info.ping = -1;
1556 // we also want to increase the serverlist_cachecount then
1557 serverlist_cachecount++;
1560 entry->query = SQS_QUERYING;
1565 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1568 if (serverlist_consoleoutput)
1569 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1572 char ipstring [128];
1575 if (data[0] == '\\')
1577 unsigned short port = data[5] * 256 + data[6];
1579 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1580 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1582 // move on to next address in packet
1587 else if (data[0] == '/' && isextended && length >= 19)
1589 unsigned short port = data[17] * 256 + data[18];
1596 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1598 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1601 dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x%%%s]:%hu",
1602 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1603 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1609 dpsnprintf (ipstring, sizeof (ipstring), "[%x:%x:%x:%x:%x:%x:%x:%x]:%hu",
1610 (data[1] << 8) | data[2], (data[3] << 8) | data[4], (data[5] << 8) | data[6], (data[7] << 8) | data[8],
1611 (data[9] << 8) | data[10], (data[11] << 8) | data[12], (data[13] << 8) | data[14], (data[15] << 8) | data[16],
1616 // move on to next address in packet
1622 Con_Print("Error while parsing the server list\n");
1626 if (serverlist_consoleoutput && developer_networking.integer)
1627 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1629 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1635 // begin or resume serverlist queries
1636 serverlist_querysleep = false;
1637 serverlist_querywaittime = realtime + 3;
1640 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1642 qboolean fromserver;
1643 int ret, c, control;
1645 char *string, addressstring2[128], ipstring[32];
1646 char stringbuf[16384];
1647 char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
1650 // quakeworld ingame packet
1651 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1653 // convert the address to a string incase we need it
1654 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1656 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1658 // received a command string - strip off the packaging and put it
1659 // into our string buffer with NULL termination
1662 length = min(length, (int)sizeof(stringbuf) - 1);
1663 memcpy(stringbuf, data, length);
1664 stringbuf[length] = 0;
1667 if (developer_networking.integer)
1669 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1670 Com_HexDumpToConsole(data, length);
1673 sendlength = sizeof(senddata) - 4;
1674 switch(Crypto_ClientParsePacket(string, length, senddata+4, &sendlength, peeraddress))
1676 case CRYPTO_NOMATCH:
1682 memcpy(senddata, "\377\377\377\377", 4);
1683 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1686 case CRYPTO_DISCARD:
1689 memcpy(senddata, "\377\377\377\377", 4);
1690 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
1694 case CRYPTO_REPLACE:
1695 string = senddata+4;
1696 length = sendlength;
1700 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1703 for (j = 0;j < MAX_RCONS;j++)
1705 // note: this value from i is used outside the loop too...
1706 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1707 if(cls.rcon_commands[i][0])
1708 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1717 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1718 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1720 e = strchr(rcon_password.string, ' ');
1721 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1723 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1727 strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1728 NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1729 cls.rcon_commands[i][0] = 0;
1732 for (k = 0;k < MAX_RCONS;k++)
1733 if(cls.rcon_commands[k][0])
1734 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1739 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1740 // extend the timeout on other requests as we asked for a challenge
1741 for (l = 0;l < MAX_RCONS;l++)
1742 if(cls.rcon_commands[l][0])
1743 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1744 cls.rcon_timeout[l] = realtime + rcon_secure_challengetimeout.value;
1747 return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1751 if (length >= 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1753 // darkplaces or quake3
1754 char protocolnames[1400];
1755 Protocol_Names(protocolnames, sizeof(protocolnames));
1756 Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1757 M_Update_Return_Reason("Got challenge response");
1758 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1759 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1760 // TODO: add userinfo stuff here instead of using NQ commands?
1761 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s%s\\challenge\\%s", protocolnames, cls.connect_userinfo, string + 10), peeraddress);
1764 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1766 // darkplaces or quake3
1767 M_Update_Return_Reason("Accepted");
1768 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1771 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1773 char rejectreason[128];
1774 cls.connect_trying = false;
1776 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1777 memcpy(rejectreason, string, length);
1778 rejectreason[length] = 0;
1779 M_Update_Return_Reason(rejectreason);
1782 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1784 serverlist_info_t *info;
1789 // search the cache for this server and update it
1790 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1794 info = &serverlist_cache[n].info;
1799 info->qcstatus[0] = 0;
1800 info->players[0] = 0;
1801 info->protocol = -1;
1802 info->numplayers = 0;
1804 info->maxplayers = 0;
1805 info->gameversion = 0;
1807 p = strchr(string, '\n');
1810 *p = 0; // cut off the string there
1814 Con_Printf("statusResponse without players block?\n");
1816 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1817 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1818 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1819 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1820 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1821 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1822 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1823 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1824 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1825 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1826 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1827 info->numhumans = info->numplayers - max(0, info->numbots);
1828 info->freeslots = info->maxplayers - info->numplayers;
1830 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1834 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1836 serverlist_info_t *info;
1840 // search the cache for this server and update it
1841 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1845 info = &serverlist_cache[n].info;
1850 info->qcstatus[0] = 0;
1851 info->players[0] = 0;
1852 info->protocol = -1;
1853 info->numplayers = 0;
1855 info->maxplayers = 0;
1856 info->gameversion = 0;
1858 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1859 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1860 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1861 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1862 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1863 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1864 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1865 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1866 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1867 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1868 info->numhumans = info->numplayers - max(0, info->numbots);
1869 info->freeslots = info->maxplayers - info->numplayers;
1871 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1875 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1877 // Extract the IP addresses
1880 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1883 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1885 // Extract the IP addresses
1888 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1891 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1893 // Extract the IP addresses
1897 if (serverlist_consoleoutput)
1898 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1899 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1901 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1902 if (serverlist_consoleoutput && developer_networking.integer)
1903 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1905 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1909 // move on to next address in packet
1913 // begin or resume serverlist queries
1914 serverlist_querysleep = false;
1915 serverlist_querywaittime = realtime + 3;
1918 if (!strncmp(string, "extResponse ", 12))
1920 ++cl_net_extresponse_count;
1921 if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1922 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1923 cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1924 dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1927 if (!strncmp(string, "ping", 4))
1929 if (developer_extra.integer)
1930 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1931 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1934 if (!strncmp(string, "ack", 3))
1936 // QuakeWorld compatibility
1937 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1939 // challenge message
1940 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1941 M_Update_Return_Reason("Got QuakeWorld challenge response");
1942 cls.qw_qport = qport.integer;
1943 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1944 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1945 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo, cls.connect_userinfo), peeraddress);
1948 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1951 M_Update_Return_Reason("QuakeWorld Accepted");
1952 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1955 if (length > 2 && !memcmp(string, "n\\", 2))
1957 serverlist_info_t *info;
1961 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1962 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1965 // search the cache for this server and update it
1966 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1970 info = &serverlist_cache[n].info;
1971 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1972 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1973 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1974 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1976 info->numplayers = 0; // updated below
1977 info->numhumans = 0; // updated below
1978 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1979 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1981 // count active players on server
1982 // (we could gather more info, but we're just after the number)
1983 s = strchr(string, '\n');
1987 while (s < string + length)
1989 for (;s < string + length && *s != '\n';s++)
1991 if (s >= string + length)
1999 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2003 if (string[0] == 'n')
2006 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
2008 // we may not have liked the packet, but it was a command packet, so
2009 // we're done processing this packet now
2012 // quakeworld ingame packet
2013 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2016 CL_ParseServerMessage();
2019 // netquake control packets, supported for compatibility only
2020 if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length && !ENCRYPTION_REQUIRED)
2023 serverlist_info_t *info;
2027 SZ_Clear(&net_message);
2028 SZ_Write(&net_message, data, length);
2034 if (developer_extra.integer)
2035 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
2036 if (cls.connect_trying)
2038 lhnetaddress_t clientportaddress;
2039 clientportaddress = *peeraddress;
2040 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
2041 // extra ProQuake stuff
2043 cls.proquake_servermod = MSG_ReadByte(); // MOD_PROQUAKE
2045 cls.proquake_servermod = 0;
2047 cls.proquake_serverversion = MSG_ReadByte(); // version * 10
2049 cls.proquake_serverversion = 0;
2051 cls.proquake_serverflags = MSG_ReadByte(); // flags (mainly PQF_CHEATFREE)
2053 cls.proquake_serverflags = 0;
2054 if (cls.proquake_servermod == 1)
2055 Con_Printf("Connected to ProQuake %.1f server, enabling precise aim\n", cls.proquake_serverversion / 10.0f);
2056 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
2057 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
2058 M_Update_Return_Reason("Accepted");
2059 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
2063 if (developer_extra.integer)
2064 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
2065 cls.connect_trying = false;
2066 M_Update_Return_Reason((char *)MSG_ReadString());
2068 case CCREP_SERVER_INFO:
2069 if (developer_extra.integer)
2070 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
2071 // LordHavoc: because the quake server may report weird addresses
2072 // we just ignore it and keep the real address
2074 // search the cache for this server and update it
2075 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
2079 info = &serverlist_cache[n].info;
2080 strlcpy(info->game, "Quake", sizeof(info->game));
2081 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
2082 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
2083 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
2084 info->numplayers = MSG_ReadByte();
2085 info->maxplayers = MSG_ReadByte();
2086 info->protocol = MSG_ReadByte();
2088 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
2091 case CCREP_RCON: // RocketGuy: ProQuake rcon support
2092 if (developer_extra.integer)
2093 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
2095 Con_Printf("%s\n", MSG_ReadString());
2097 case CCREP_PLAYER_INFO:
2098 // we got a CCREP_PLAYER_INFO??
2099 //if (developer_extra.integer)
2100 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
2102 case CCREP_RULE_INFO:
2103 // we got a CCREP_RULE_INFO??
2104 //if (developer_extra.integer)
2105 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
2110 SZ_Clear(&net_message);
2111 // we may not have liked the packet, but it was a valid control
2112 // packet, so we're done processing this packet now
2116 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2117 CL_ParseServerMessage();
2121 void NetConn_QueryQueueFrame(void)
2127 static double querycounter = 0;
2129 if(!net_slist_pause.integer && serverlist_paused)
2130 ServerList_RebuildViewList();
2131 serverlist_paused = net_slist_pause.integer != 0;
2133 if (serverlist_querysleep)
2136 // apply a cool down time after master server replies,
2137 // to avoid messing up the ping times on the servers
2138 if (serverlist_querywaittime > realtime)
2141 // each time querycounter reaches 1.0 issue a query
2142 querycounter += cl.realframetime * net_slist_queriespersecond.value;
2143 maxqueries = (int)querycounter;
2144 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2145 querycounter -= maxqueries;
2147 if( maxqueries == 0 ) {
2151 // scan serverlist and issue queries as needed
2152 serverlist_querysleep = true;
2154 timeouttime = realtime - net_slist_timeout.value;
2155 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
2157 serverlist_entry_t *entry = &serverlist_cache[ index ];
2158 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2163 serverlist_querysleep = false;
2164 if( entry->querycounter != 0 && entry->querytime > timeouttime )
2169 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
2171 lhnetaddress_t address;
2174 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2175 if (entry->protocol == PROTOCOL_QUAKEWORLD)
2177 for (socket = 0; socket < cl_numsockets ; socket++)
2178 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2182 for (socket = 0; socket < cl_numsockets ; socket++)
2183 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2186 // update the entry fields
2187 entry->querytime = realtime;
2188 entry->querycounter++;
2190 // if not in the slist menu we should print the server to console
2191 if (serverlist_consoleoutput)
2192 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2198 // have we tried to refresh this server?
2199 if( entry->query == SQS_REFRESHING ) {
2200 // yes, so update the reply count (since its not responding anymore)
2202 if(!serverlist_paused)
2203 ServerList_ViewList_Remove(entry);
2205 entry->query = SQS_TIMEDOUT;
2210 void NetConn_ClientFrame(void)
2213 lhnetaddress_t peeraddress;
2214 NetConn_UpdateSockets();
2215 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2217 if (cls.connect_remainingtries == 0)
2218 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2219 cls.connect_nextsendtime = realtime + 1;
2220 cls.connect_remainingtries--;
2221 if (cls.connect_remainingtries <= -10)
2223 cls.connect_trying = false;
2224 M_Update_Return_Reason("Connect: Failed");
2227 // try challenge first (newer DP server or QW)
2228 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2229 // then try netquake as a fallback (old server, or netquake)
2230 SZ_Clear(&net_message);
2231 // save space for the header, filled in later
2232 MSG_WriteLong(&net_message, 0);
2233 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2234 MSG_WriteString(&net_message, "QUAKE");
2235 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2236 // extended proquake stuff
2237 MSG_WriteByte(&net_message, 1); // mod = MOD_PROQUAKE
2238 // this version matches ProQuake 3.40, the first version to support
2239 // the NAT fix, and it only supports the NAT fix for ProQuake 3.40 or
2240 // higher clients, so we pretend we are that version...
2241 MSG_WriteByte(&net_message, 34); // version * 10
2242 MSG_WriteByte(&net_message, 0); // flags
2243 MSG_WriteLong(&net_message, 0); // password
2244 // write the packetsize now...
2245 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2246 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2247 SZ_Clear(&net_message);
2249 for (i = 0;i < cl_numsockets;i++)
2251 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2253 // R_TimeReport("clientreadnetwork");
2254 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2255 // R_TimeReport("clientparsepacket");
2258 NetConn_QueryQueueFrame();
2259 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2261 Con_Print("Connection timed out\n");
2263 Host_ShutdownServer ();
2267 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2271 for (i = 0;i < bufferlength - 1;i++)
2275 c = rand () % (127 - 33) + 33;
2276 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2282 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2283 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2286 unsigned int nb_clients = 0, nb_bots = 0, i;
2289 const char *crypto_idstring;
2294 // How many clients are there?
2295 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2297 if (svs.clients[i].active)
2300 if (!svs.clients[i].netconnection)
2306 str = PRVM_GetString(PRVM_serverglobalstring(worldstatus));
2312 for(q = str; *q && (size_t)((p - qcstatus) < (sizeof(qcstatus)) - 1); ++q)
2313 if(*q != '\\' && *q != '\n')
2318 /// \TODO: we should add more information for the full status string
2319 crypto_idstring = Crypto_GetInfoResponseDataString();
2320 length = dpsnprintf(out_msg, out_size,
2321 "\377\377\377\377%s\x0A"
2322 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2323 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2328 fullstatus ? "statusResponse" : "infoResponse",
2329 gamename, com_modname, gameversion.integer, svs.maxclients,
2330 nb_clients, nb_bots, sv.worldbasename, hostname.string, NET_PROTOCOL_VERSION,
2331 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2332 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2333 crypto_idstring ? "\\d0_blind_id\\" : "", crypto_idstring ? crypto_idstring : "",
2334 fullstatus ? "\n" : "");
2336 // Make sure it fits in the buffer
2346 savelength = length;
2348 ptr = out_msg + length;
2349 left = (int)out_size - length;
2351 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2353 client_t *cl = &svs.clients[i];
2356 int nameind, cleanind, pingvalue;
2358 char cleanname [sizeof(cl->name)];
2362 // Remove all characters '"' and '\' in the player name
2367 curchar = cl->name[nameind++];
2368 if (curchar != '"' && curchar != '\\')
2370 cleanname[cleanind++] = curchar;
2371 if (cleanind == sizeof(cleanname) - 1)
2374 } while (curchar != '\0');
2375 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2377 pingvalue = (int)(cl->ping * 1000.0f);
2378 if(cl->netconnection)
2379 pingvalue = bound(1, pingvalue, 9999);
2384 ed = PRVM_EDICT_NUM(i + 1);
2385 str = PRVM_GetString(PRVM_serveredictstring(ed, clientstatus));
2391 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2392 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2397 if ((gamemode == GAME_NEXUIZ || gamemode == GAME_XONOTIC) && (teamplay.integer > 0))
2399 if(cl->frags == -666) // spectator
2400 strlcpy(teambuf, " 0", sizeof(teambuf));
2401 else if(cl->colors == 0x44) // red team
2402 strlcpy(teambuf, " 1", sizeof(teambuf));
2403 else if(cl->colors == 0xDD) // blue team
2404 strlcpy(teambuf, " 2", sizeof(teambuf));
2405 else if(cl->colors == 0xCC) // yellow team
2406 strlcpy(teambuf, " 3", sizeof(teambuf));
2407 else if(cl->colors == 0x99) // pink team
2408 strlcpy(teambuf, " 4", sizeof(teambuf));
2410 strlcpy(teambuf, " 0", sizeof(teambuf));
2415 // note: team number is inserted according to SoF2 protocol
2417 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2423 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2432 // turn it into an infoResponse!
2433 out_msg[savelength] = 0;
2434 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2435 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2452 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2454 int floodslotnum, bestfloodslotnum;
2455 double bestfloodtime;
2456 lhnetaddress_t noportpeeraddress;
2457 // see if this is a connect flood
2458 noportpeeraddress = *peeraddress;
2459 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2460 bestfloodslotnum = 0;
2461 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2462 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2464 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2466 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2467 bestfloodslotnum = floodslotnum;
2469 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2471 // this address matches an ongoing flood address
2472 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2474 // renew the ban on this address so it does not expire
2475 // until the flood has subsided
2476 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2477 //Con_Printf("Flood detected!\n");
2480 // the flood appears to have subsided, so allow this
2481 bestfloodslotnum = floodslotnum; // reuse the same slot
2485 // begin a new timeout on this address
2486 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2487 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2488 //Con_Printf("Flood detection initiated!\n");
2492 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2495 lhnetaddress_t noportpeeraddress;
2496 // see if this is a connect flood
2497 noportpeeraddress = *peeraddress;
2498 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2499 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2501 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2503 // this address matches an ongoing flood address
2505 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2506 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2507 //Con_Printf("Flood cleared!\n");
2512 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2514 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2519 t1 = (long) time(NULL);
2520 t2 = strtol(s, NULL, 0);
2521 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2524 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2527 return !memcmp(mdfourbuf, hash, 16);
2530 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2535 if(slen < (int)(sizeof(challenge[0].string)) - 1)
2538 // validate the challenge
2539 for (i = 0;i < MAX_CHALLENGES;i++)
2540 if(challenge[i].time > 0)
2541 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2543 // if the challenge is not recognized, drop the packet
2544 if (i == MAX_CHALLENGES)
2547 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2550 if(memcmp(mdfourbuf, hash, 16))
2553 // unmark challenge to prevent replay attacks
2554 challenge[i].time = 0;
2559 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2561 return !strcmp(password, hash);
2564 /// returns a string describing the user level, or NULL for auth failure
2565 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)
2567 const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2568 static char buf[MAX_INPUTLINE];
2570 qboolean restricted = false;
2571 qboolean have_usernames = false;
2573 userpass_start = rcon_password.string;
2574 while((userpass_end = strchr(userpass_start, ' ')))
2576 have_usernames = true;
2577 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2579 if(comparator(peeraddress, buf, password, cs, cslen))
2581 userpass_start = userpass_end + 1;
2583 if(userpass_start[0])
2585 userpass_end = userpass_start + strlen(userpass_start);
2586 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2591 have_usernames = false;
2592 userpass_start = rcon_restricted_password.string;
2593 while((userpass_end = strchr(userpass_start, ' ')))
2595 have_usernames = true;
2596 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2598 if(comparator(peeraddress, buf, password, cs, cslen))
2600 userpass_start = userpass_end + 1;
2602 if(userpass_start[0])
2604 userpass_end = userpass_start + strlen(userpass_start);
2605 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2609 return NULL; // DENIED
2612 for(text = s; text != endpos; ++text)
2613 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2614 return NULL; // block possible exploits against the parser/alias expansion
2618 size_t l = strlen(s);
2621 hasquotes = (strchr(s, '"') != NULL);
2622 // sorry, we can't allow these substrings in wildcard expressions,
2623 // as they can mess with the argument counts
2624 text = rcon_restricted_commands.string;
2625 while(COM_ParseToken_Console(&text))
2627 // com_token now contains a pattern to check for...
2628 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2631 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2634 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2636 if(!strcmp(com_token, s))
2639 else // single-arg expression? must match the beginning of the command
2641 if(!strcmp(com_token, s))
2643 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2647 // if we got here, nothing matched!
2655 userpass_startpass = strchr(userpass_start, ':');
2656 if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2657 return va("%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2659 return va("%srcon", restricted ? "restricted " : "");
2662 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos, qboolean proquakeprotocol)
2666 // looks like a legitimate rcon command with the correct password
2667 const char *s_ptr = s;
2668 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2669 while(s_ptr != endpos)
2671 size_t l = strlen(s_ptr);
2673 Con_Printf(" %s;", s_ptr);
2678 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2679 Con_Rcon_Redirect_Init(mysocket, peeraddress, proquakeprotocol);
2682 size_t l = strlen(s);
2685 client_t *host_client_save = host_client;
2686 Cmd_ExecuteString(s, src_command);
2687 host_client = host_client_save;
2688 // in case it is a command that changes host_client (like restart)
2692 Con_Rcon_Redirect_End();
2696 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2700 extern void SV_SendServerinfo (client_t *client);
2701 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2703 int i, ret, clientnum, best;
2706 char *s, *string, response[1400], addressstring2[128];
2707 static char stringbuf[16384];
2708 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2709 char senddata[NET_HEADERSIZE+NET_MAXMESSAGE+CRYPTO_HEADERSIZE];
2710 size_t sendlength, response_len;
2715 // convert the address to a string incase we need it
2716 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2718 // see if we can identify the sender as a local player
2719 // (this is necessary for rcon to send a reliable reply if the client is
2720 // actually on the server, not sending remotely)
2721 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2722 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2724 if (i == svs.maxclients)
2727 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2729 // received a command string - strip off the packaging and put it
2730 // into our string buffer with NULL termination
2733 length = min(length, (int)sizeof(stringbuf) - 1);
2734 memcpy(stringbuf, data, length);
2735 stringbuf[length] = 0;
2738 if (developer_extra.integer)
2740 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2741 Com_HexDumpToConsole(data, length);
2744 sendlength = sizeof(senddata) - 4;
2745 switch(Crypto_ServerParsePacket(string, length, senddata+4, &sendlength, peeraddress))
2747 case CRYPTO_NOMATCH:
2753 memcpy(senddata, "\377\377\377\377", 4);
2754 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2757 case CRYPTO_DISCARD:
2760 memcpy(senddata, "\377\377\377\377", 4);
2761 NetConn_Write(mysocket, senddata, sendlength+4, peeraddress);
2765 case CRYPTO_REPLACE:
2766 string = senddata+4;
2767 length = sendlength;
2771 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -3))
2773 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2775 if(challenge[i].time > 0)
2776 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2778 if (besttime > challenge[i].time)
2779 besttime = challenge[best = i].time;
2781 // if we did not find an exact match, choose the oldest and
2782 // update address and string
2783 if (i == MAX_CHALLENGES)
2786 challenge[i].address = *peeraddress;
2787 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2789 challenge[i].time = realtime;
2790 // send the challenge
2791 dpsnprintf(response, sizeof(response), "\377\377\377\377challenge %s", challenge[i].string);
2792 response_len = strlen(response) + 1;
2793 Crypto_ServerAppendToChallenge(string, length, response, &response_len, sizeof(response));
2794 NetConn_Write(mysocket, response, response_len, peeraddress);
2797 if (length > 8 && !memcmp(string, "connect\\", 8))
2799 crypto_t *crypto = Crypto_ServerGetInstance(peeraddress);
2803 if(crypto && crypto->authenticated)
2805 // no need to check challenge
2806 if(crypto_developer.integer)
2808 Con_Printf("%s connection to %s is being established: client is %s@%.*s, I am %.*s@%.*s\n",
2809 crypto->use_aes ? "Encrypted" : "Authenticated",
2811 crypto->client_idfp[0] ? crypto->client_idfp : "-",
2812 crypto_keyfp_recommended_length, crypto->client_keyfp[0] ? crypto->client_keyfp : "-",
2813 crypto_keyfp_recommended_length, crypto->server_idfp[0] ? crypto->server_idfp : "-",
2814 crypto_keyfp_recommended_length, crypto->server_keyfp[0] ? crypto->server_keyfp : "-"
2820 if ((s = SearchInfostring(string, "challenge")))
2822 // validate the challenge
2823 for (i = 0;i < MAX_CHALLENGES;i++)
2824 if(challenge[i].time > 0)
2825 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2827 // if the challenge is not recognized, drop the packet
2828 if (i == MAX_CHALLENGES)
2833 if((s = SearchInfostring(string, "message")))
2834 Con_DPrintf("Connecting client %s sent us the message: %s\n", addressstring2, s);
2836 if(!(islocal || sv_public.integer > -2))
2838 if (developer_extra.integer)
2839 Con_Printf("Datagram_ParseConnectionless: sending \"reject %s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
2840 NetConn_WriteString(mysocket, va("\377\377\377\377reject %s", sv_public_rejectreason.string), peeraddress);
2844 // check engine protocol
2845 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2847 if (developer_extra.integer)
2848 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2849 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2853 // see if this is a duplicate connection request or a disconnected
2854 // client who is rejoining to the same client slot
2855 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2857 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2859 // this is a known client...
2860 if(crypto && crypto->authenticated)
2862 // reject if changing key!
2863 if(client->netconnection->crypto.authenticated)
2866 strcmp(client->netconnection->crypto.client_idfp, crypto->client_idfp)
2868 strcmp(client->netconnection->crypto.server_idfp, crypto->server_idfp)
2870 strcmp(client->netconnection->crypto.client_keyfp, crypto->client_keyfp)
2872 strcmp(client->netconnection->crypto.server_keyfp, crypto->server_keyfp)
2875 if (developer_extra.integer)
2876 Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to change key of crypto.\" to %s.\n", addressstring2);
2877 NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to change key of crypto.", peeraddress);
2884 // reject if downgrading!
2885 if(client->netconnection->crypto.authenticated)
2887 if (developer_extra.integer)
2888 Con_Printf("Datagram_ParseConnectionless: sending \"reject Attempt to downgrade crypto.\" to %s.\n", addressstring2);
2889 NetConn_WriteString(mysocket, "\377\377\377\377reject Attempt to downgrade crypto.", peeraddress);
2893 if (client->spawned)
2895 // client crashed and is coming back,
2896 // keep their stuff intact
2897 if (developer_extra.integer)
2898 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2899 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2900 if(crypto && crypto->authenticated)
2901 Crypto_ServerFinishInstance(&client->netconnection->crypto, crypto);
2903 SV_SendServerinfo(client);
2908 // client is still trying to connect,
2909 // so we send a duplicate reply
2910 if (developer_extra.integer)
2911 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2912 if(crypto && crypto->authenticated)
2913 Crypto_ServerFinishInstance(&client->netconnection->crypto, crypto);
2914 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2920 if (NetConn_PreventConnectFlood(peeraddress))
2923 // find an empty client slot for this new client
2924 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2927 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2929 // allocated connection
2930 if (developer_extra.integer)
2931 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2932 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2933 // now set up the client
2934 if(crypto && crypto->authenticated)
2935 Crypto_ServerFinishInstance(&conn->crypto, crypto);
2937 SV_ConnectClient(clientnum, conn);
2939 NetConn_Heartbeat(1);
2944 // no empty slots found - server is full
2945 if (developer_extra.integer)
2946 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2947 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2951 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2953 const char *challenge = NULL;
2955 // If there was a challenge in the getinfo message
2956 if (length > 8 && string[7] == ' ')
2957 challenge = string + 8;
2959 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2961 if (developer_extra.integer)
2962 Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
2963 NetConn_WriteString(mysocket, response, peeraddress);
2967 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2969 const char *challenge = NULL;
2971 // If there was a challenge in the getinfo message
2972 if (length > 10 && string[9] == ' ')
2973 challenge = string + 10;
2975 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2977 if (developer_extra.integer)
2978 Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
2979 NetConn_WriteString(mysocket, response, peeraddress);
2983 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2985 char *password = string + 20;
2986 char *timeval = string + 37;
2987 char *s = strchr(timeval, ' ');
2988 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2989 const char *userlevel;
2991 if(rcon_secure.integer > 1)
2995 return true; // invalid packet
2998 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2999 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3002 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
3004 char *password = string + 25;
3005 char *challenge = string + 42;
3006 char *s = strchr(challenge, ' ');
3007 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3008 const char *userlevel;
3010 return true; // invalid packet
3013 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
3014 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3017 if (length >= 5 && !memcmp(string, "rcon ", 5))
3020 char *s = string + 5;
3021 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3024 if(rcon_secure.integer > 0)
3027 for (i = 0;!ISWHITESPACE(*s);s++)
3028 if (i < (int)sizeof(password) - 1)
3030 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
3033 if (!ISWHITESPACE(password[0]))
3035 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3036 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, false);
3040 if (!strncmp(string, "extResponse ", 12))
3042 ++sv_net_extresponse_count;
3043 if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
3044 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
3045 sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
3046 dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
3049 if (!strncmp(string, "ping", 4))
3051 if (developer_extra.integer)
3052 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
3053 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
3056 if (!strncmp(string, "ack", 3))
3058 // we may not have liked the packet, but it was a command packet, so
3059 // we're done processing this packet now
3062 // netquake control packets, supported for compatibility only, and only
3063 // when running game protocols that are normally served via this connection
3065 // (this protects more modern protocols against being used for
3066 // Quake packet flood Denial Of Service attacks)
3067 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)
3071 const char *protocolname;
3074 SZ_Clear(&net_message);
3075 SZ_Write(&net_message, data, length);
3081 if (developer_extra.integer)
3082 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
3083 if(!(islocal || sv_public.integer > -2))
3085 if (developer_extra.integer)
3086 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"%s\" to %s.\n", sv_public_rejectreason.string, addressstring2);
3087 SZ_Clear(&net_message);
3088 // save space for the header, filled in later
3089 MSG_WriteLong(&net_message, 0);
3090 MSG_WriteByte(&net_message, CCREP_REJECT);
3091 MSG_WriteString(&net_message, va("%s\n", sv_public_rejectreason.string));
3092 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3093 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3094 SZ_Clear(&net_message);
3098 protocolname = MSG_ReadString();
3099 protocolnumber = MSG_ReadByte();
3100 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
3102 if (developer_extra.integer)
3103 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
3104 SZ_Clear(&net_message);
3105 // save space for the header, filled in later
3106 MSG_WriteLong(&net_message, 0);
3107 MSG_WriteByte(&net_message, CCREP_REJECT);
3108 MSG_WriteString(&net_message, "Incompatible version.\n");
3109 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3110 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3111 SZ_Clear(&net_message);
3115 // see if this connect request comes from a known client
3116 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3118 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
3120 // this is either a duplicate connection request
3121 // or coming back from a timeout
3122 // (if so, keep their stuff intact)
3125 if (developer_extra.integer)
3126 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
3127 SZ_Clear(&net_message);
3128 // save space for the header, filled in later
3129 MSG_WriteLong(&net_message, 0);
3130 MSG_WriteByte(&net_message, CCREP_ACCEPT);
3131 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
3132 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3133 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3134 SZ_Clear(&net_message);
3136 // if client is already spawned, re-send the
3137 // serverinfo message as they'll need it to play
3138 if (client->spawned)
3141 SV_SendServerinfo(client);
3148 // this is a new client, check for connection flood
3149 if (NetConn_PreventConnectFlood(peeraddress))
3152 // find a slot for the new client
3153 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
3156 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
3158 // connect to the client
3159 // everything is allocated, just fill in the details
3160 strlcpy (conn->address, addressstring2, sizeof (conn->address));
3161 if (developer_extra.integer)
3162 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
3163 // send back the info about the server connection
3164 SZ_Clear(&net_message);
3165 // save space for the header, filled in later
3166 MSG_WriteLong(&net_message, 0);
3167 MSG_WriteByte(&net_message, CCREP_ACCEPT);
3168 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
3169 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3170 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3171 SZ_Clear(&net_message);
3172 // now set up the client struct
3174 SV_ConnectClient(clientnum, conn);
3176 NetConn_Heartbeat(1);
3181 if (developer_extra.integer)
3182 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
3183 // no room; try to let player know
3184 SZ_Clear(&net_message);
3185 // save space for the header, filled in later
3186 MSG_WriteLong(&net_message, 0);
3187 MSG_WriteByte(&net_message, CCREP_REJECT);
3188 MSG_WriteString(&net_message, "Server is full.\n");
3189 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3190 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3191 SZ_Clear(&net_message);
3193 case CCREQ_SERVER_INFO:
3194 if (developer_extra.integer)
3195 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
3196 if(!(islocal || sv_public.integer > -1))
3198 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
3201 char myaddressstring[128];
3202 if (developer_extra.integer)
3203 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
3204 SZ_Clear(&net_message);
3205 // save space for the header, filled in later
3206 MSG_WriteLong(&net_message, 0);
3207 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
3208 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
3209 MSG_WriteString(&net_message, myaddressstring);
3210 MSG_WriteString(&net_message, hostname.string);
3211 MSG_WriteString(&net_message, sv.name);
3212 // How many clients are there?
3213 for (i = 0, numclients = 0;i < svs.maxclients;i++)
3214 if (svs.clients[i].active)
3216 MSG_WriteByte(&net_message, numclients);
3217 MSG_WriteByte(&net_message, svs.maxclients);
3218 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3219 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3220 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3221 SZ_Clear(&net_message);
3224 case CCREQ_PLAYER_INFO:
3225 if (developer_extra.integer)
3226 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
3227 if(!(islocal || sv_public.integer > -1))
3231 int playerNumber, activeNumber, clientNumber;
3234 playerNumber = MSG_ReadByte();
3236 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3237 if (client->active && ++activeNumber == playerNumber)
3239 if (clientNumber != svs.maxclients)
3241 SZ_Clear(&net_message);
3242 // save space for the header, filled in later
3243 MSG_WriteLong(&net_message, 0);
3244 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
3245 MSG_WriteByte(&net_message, playerNumber);
3246 MSG_WriteString(&net_message, client->name);
3247 MSG_WriteLong(&net_message, client->colors);
3248 MSG_WriteLong(&net_message, client->frags);
3249 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
3250 if(sv_status_privacy.integer)
3251 MSG_WriteString(&net_message, client->netconnection ? "hidden" : "botclient");
3253 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
3254 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3255 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3256 SZ_Clear(&net_message);
3260 case CCREQ_RULE_INFO:
3261 if (developer_extra.integer)
3262 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3263 if(!(islocal || sv_public.integer > -1))
3270 // find the search start location
3271 prevCvarName = MSG_ReadString();
3272 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3274 // send the response
3275 SZ_Clear(&net_message);
3276 // save space for the header, filled in later
3277 MSG_WriteLong(&net_message, 0);
3278 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
3281 MSG_WriteString(&net_message, var->name);
3282 MSG_WriteString(&net_message, var->string);
3284 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3285 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3286 SZ_Clear(&net_message);
3290 if (developer_extra.integer)
3291 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RCON from %s.\n", addressstring2);
3292 if (sv.active && !rcon_secure.integer)
3294 char password[2048];
3298 const char *userlevel;
3299 strlcpy(password, MSG_ReadString(), sizeof(password));
3300 strlcpy(cmd, MSG_ReadString(), sizeof(cmd));
3302 endpos = cmd + strlen(cmd) + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
3303 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
3304 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos, true);
3311 SZ_Clear(&net_message);
3312 // we may not have liked the packet, but it was a valid control
3313 // packet, so we're done processing this packet now
3318 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3321 SV_ReadClientMessage();
3329 void NetConn_ServerFrame(void)
3332 lhnetaddress_t peeraddress;
3333 for (i = 0;i < sv_numsockets;i++)
3334 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3335 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3336 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3338 // never timeout loopback connections
3339 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3341 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3343 SV_DropClient(false);
3349 void NetConn_SleepMicroseconds(int microseconds)
3351 LHNET_SleepUntilPacket_Microseconds(microseconds);
3354 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3358 lhnetaddress_t masteraddress;
3359 lhnetaddress_t broadcastaddress;
3362 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3365 // 26000 is the default quake server port, servers on other ports will not
3367 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3368 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3372 for (i = 0;i < cl_numsockets;i++)
3376 const char *cmdname, *extraoptions;
3377 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3379 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3381 // search LAN for Quake servers
3382 SZ_Clear(&net_message);
3383 // save space for the header, filled in later
3384 MSG_WriteLong(&net_message, 0);
3385 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
3386 MSG_WriteString(&net_message, "QUAKE");
3387 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3388 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3389 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
3390 SZ_Clear(&net_message);
3392 // search LAN for DarkPlaces servers
3393 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3396 // build the getservers message to send to the dpmaster master servers
3397 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3399 cmdname = "getserversExt";
3400 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
3404 cmdname = "getservers";
3407 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3410 for (masternum = 0;sv_masters[masternum].name;masternum++)
3412 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3415 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3419 // search favorite servers
3420 for(j = 0; j < nFavorites; ++j)
3422 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3424 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3425 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3432 // only query QuakeWorld servers when the user wants to
3435 for (i = 0;i < cl_numsockets;i++)
3439 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3441 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3443 // search LAN for QuakeWorld servers
3444 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3446 // build the getservers message to send to the qwmaster master servers
3447 // note this has no -1 prefix, and the trailing nul byte is sent
3448 dpsnprintf(request, sizeof(request), "c\n");
3452 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3454 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3456 if (m_state != m_slist)
3458 char lookupstring[128];
3459 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3460 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3463 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3467 // search favorite servers
3468 for(j = 0; j < nFavorites; ++j)
3470 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3472 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3474 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3475 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3482 if (!masterquerycount)
3484 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3485 M_Update_Return_Reason("No network");
3489 void NetConn_Heartbeat(int priority)
3491 lhnetaddress_t masteraddress;
3493 lhnetsocket_t *mysocket;
3495 // if it's a state change (client connected), limit next heartbeat to no
3496 // more than 30 sec in the future
3497 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3498 nextheartbeattime = realtime + 30.0;
3500 // limit heartbeatperiod to 30 to 270 second range,
3501 // lower limit is to avoid abusing master servers with excess traffic,
3502 // upper limit is to avoid timing out on the master server (which uses
3504 if (sv_heartbeatperiod.value < 30)
3505 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3506 if (sv_heartbeatperiod.value > 270)
3507 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3509 // make advertising optional and don't advertise singleplayer games, and
3510 // only send a heartbeat as often as the admin wants
3511 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3513 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3514 for (masternum = 0;sv_masters[masternum].name;masternum++)
3515 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3516 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3520 static void Net_Heartbeat_f(void)
3523 NetConn_Heartbeat(2);
3525 Con_Print("No server running, can not heartbeat to master server.\n");
3528 void PrintStats(netconn_t *conn)
3530 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3531 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3533 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3536 void Net_Stats_f(void)
3539 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3540 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3541 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3542 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3543 Con_Printf("packetsSent = %i\n", packetsSent);
3544 Con_Printf("packetsReSent = %i\n", packetsReSent);
3545 Con_Printf("packetsReceived = %i\n", packetsReceived);
3546 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3547 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3548 Con_Print("connections =\n");
3549 for (conn = netconn_list;conn;conn = conn->next)
3553 void Net_Refresh_f(void)
3555 if (m_state != m_slist) {
3556 Con_Print("Sending new requests to master servers\n");
3557 ServerList_QueryList(false, true, false, true);
3558 Con_Print("Listening for replies...\n");
3560 ServerList_QueryList(false, true, false, false);
3563 void Net_Slist_f(void)
3565 ServerList_ResetMasks();
3566 serverlist_sortbyfield = SLIF_PING;
3567 serverlist_sortflags = 0;
3568 if (m_state != m_slist) {
3569 Con_Print("Sending requests to master servers\n");
3570 ServerList_QueryList(true, true, false, true);
3571 Con_Print("Listening for replies...\n");
3573 ServerList_QueryList(true, true, false, false);
3576 void Net_SlistQW_f(void)
3578 ServerList_ResetMasks();
3579 serverlist_sortbyfield = SLIF_PING;
3580 serverlist_sortflags = 0;
3581 if (m_state != m_slist) {
3582 Con_Print("Sending requests to master servers\n");
3583 ServerList_QueryList(true, false, true, true);
3584 serverlist_consoleoutput = true;
3585 Con_Print("Listening for replies...\n");
3587 ServerList_QueryList(true, false, true, false);
3590 void NetConn_Init(void)
3593 lhnetaddress_t tempaddress;
3594 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3595 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3596 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3597 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3598 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3599 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3600 Cvar_RegisterVariable(&rcon_restricted_password);
3601 Cvar_RegisterVariable(&rcon_restricted_commands);
3602 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3603 Cvar_RegisterVariable(&net_slist_queriespersecond);
3604 Cvar_RegisterVariable(&net_slist_queriesperframe);
3605 Cvar_RegisterVariable(&net_slist_timeout);
3606 Cvar_RegisterVariable(&net_slist_maxtries);
3607 Cvar_RegisterVariable(&net_slist_favorites);
3608 Cvar_RegisterVariable(&net_slist_pause);
3609 Cvar_RegisterVariable(&net_messagetimeout);
3610 Cvar_RegisterVariable(&net_connecttimeout);
3611 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3612 Cvar_RegisterVariable(&cl_netlocalping);
3613 Cvar_RegisterVariable(&cl_netpacketloss_send);
3614 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3615 Cvar_RegisterVariable(&hostname);
3616 Cvar_RegisterVariable(&developer_networking);
3617 Cvar_RegisterVariable(&cl_netport);
3618 Cvar_RegisterVariable(&sv_netport);
3619 Cvar_RegisterVariable(&net_address);
3620 Cvar_RegisterVariable(&net_address_ipv6);
3621 Cvar_RegisterVariable(&sv_public);
3622 Cvar_RegisterVariable(&sv_public_rejectreason);
3623 Cvar_RegisterVariable(&sv_heartbeatperiod);
3624 for (i = 0;sv_masters[i].name;i++)
3625 Cvar_RegisterVariable(&sv_masters[i]);
3626 Cvar_RegisterVariable(&gameversion);
3627 Cvar_RegisterVariable(&gameversion_min);
3628 Cvar_RegisterVariable(&gameversion_max);
3629 // 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.
3630 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3632 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3634 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3635 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3638 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3640 // 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
3641 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3643 i = atoi(com_argv[i + 1]);
3644 if (i >= 0 && i < 65536)
3646 Con_Printf("-port option used, setting port cvar to %i\n", i);
3647 Cvar_SetValueQuick(&sv_netport, i);
3650 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3654 net_message.data = net_message_buf;
3655 net_message.maxsize = sizeof(net_message_buf);
3656 net_message.cursize = 0;
3660 void NetConn_Shutdown(void)
3662 NetConn_CloseClientPorts();
3663 NetConn_CloseServerPorts();