2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 // for secure rcon authentication
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
34 // note this defaults on for dedicated servers, off for listen servers
35 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
36 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
38 static cvar_t sv_masters [] =
40 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
41 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
42 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
43 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
44 {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
45 {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
46 {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
50 static cvar_t sv_qwmasters [] =
52 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
53 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
54 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
55 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
56 {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
57 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
58 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
59 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
60 {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
64 static double nextheartbeattime = 0;
66 sizebuf_t net_message;
67 static unsigned char net_message_buf[NET_MAXMESSAGE];
69 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
70 cvar_t net_connecttimeout = {0, "net_connecttimeout","15", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods). Must be above 10 seconds."};
71 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
72 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
73 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
75 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
76 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
77 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
78 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
79 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
80 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
81 static cvar_t net_slist_pause = {0, "net_slist_pause", "0", "when set to 1, the server list won't update until it is set back to 0"};
82 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
83 static cvar_t net_slist_favorites = {CVAR_SAVE | CVAR_NQUSERINFOHACK, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
84 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific) to be sent to querying clients"};
85 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"};
86 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"};
87 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"};
88 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
89 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)"};
90 extern cvar_t rcon_secure;
91 extern cvar_t rcon_secure_challengetimeout;
93 /* statistic counters */
94 static int packetsSent = 0;
95 static int packetsReSent = 0;
96 static int packetsReceived = 0;
97 static int receivedDuplicateCount = 0;
98 static int droppedDatagrams = 0;
100 static int unreliableMessagesSent = 0;
101 static int unreliableMessagesReceived = 0;
102 static int reliableMessagesSent = 0;
103 static int reliableMessagesReceived = 0;
105 double masterquerytime = -1000;
106 int masterquerycount = 0;
107 int masterreplycount = 0;
108 int serverquerycount = 0;
109 int serverreplycount = 0;
111 /// this is only false if there are still servers left to query
112 static qboolean serverlist_querysleep = true;
113 static qboolean serverlist_paused = false;
114 /// this is pushed a second or two ahead of realtime whenever a master server
115 /// reply is received, to avoid issuing queries while master replies are still
116 /// flooding in (which would make a mess of the ping times)
117 static double serverlist_querywaittime = 0;
119 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
120 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
122 static int cl_numsockets;
123 static lhnetsocket_t *cl_sockets[16];
124 static int sv_numsockets;
125 static lhnetsocket_t *sv_sockets[16];
127 netconn_t *netconn_list = NULL;
128 mempool_t *netconn_mempool = NULL;
130 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
131 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
132 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
133 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
135 char cl_net_extresponse[NET_EXTRESPONSE_MAX][1400];
136 int cl_net_extresponse_count = 0;
137 int cl_net_extresponse_last = 0;
139 char sv_net_extresponse[NET_EXTRESPONSE_MAX][1400];
140 int sv_net_extresponse_count = 0;
141 int sv_net_extresponse_last = 0;
143 // ServerList interface
144 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
145 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
147 serverlist_infofield_t serverlist_sortbyfield;
148 int serverlist_sortflags;
150 int serverlist_viewcount = 0;
151 unsigned short serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
153 int serverlist_maxcachecount = 0;
154 int serverlist_cachecount = 0;
155 serverlist_entry_t *serverlist_cache = NULL;
157 qboolean serverlist_consoleoutput;
159 static int nFavorites = 0;
160 static lhnetaddress_t favorites[MAX_FAVORITESERVERS];
162 void NetConn_UpdateFavorites(void)
166 p = net_slist_favorites.string;
167 while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
169 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
174 /// helper function to insert a value into the viewset
175 /// spare entries will be removed
176 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
179 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
180 i = serverlist_viewcount++;
182 i = SERVERLIST_VIEWLISTSIZE - 1;
185 for( ; i > index ; i-- )
186 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
188 serverlist_viewlist[index] = (int)(entry - serverlist_cache);
191 /// we suppose serverlist_viewcount to be valid, ie > 0
192 static void _ServerList_ViewList_Helper_Remove( int index )
194 serverlist_viewcount--;
195 for( ; index < serverlist_viewcount ; index++ )
196 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
199 /// \returns true if A should be inserted before B
200 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
202 int result = 0; // > 0 if for numbers A > B and for text if A < B
204 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
206 if(A->info.isfavorite != B->info.isfavorite)
207 return A->info.isfavorite;
210 switch( serverlist_sortbyfield ) {
212 result = A->info.ping - B->info.ping;
214 case SLIF_MAXPLAYERS:
215 result = A->info.maxplayers - B->info.maxplayers;
217 case SLIF_NUMPLAYERS:
218 result = A->info.numplayers - B->info.numplayers;
221 result = A->info.numbots - B->info.numbots;
224 result = A->info.numhumans - B->info.numhumans;
227 result = A->info.freeslots - B->info.freeslots;
230 result = A->info.protocol - B->info.protocol;
233 result = strcmp( B->info.cname, A->info.cname );
236 result = strcasecmp( B->info.game, A->info.game );
239 result = strcasecmp( B->info.map, A->info.map );
242 result = strcasecmp( B->info.mod, A->info.mod );
245 result = strcasecmp( B->info.name, A->info.name );
248 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
250 case SLIF_ISFAVORITE:
251 result = !!B->info.isfavorite - !!A->info.isfavorite;
254 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
260 if( serverlist_sortflags & SLSF_DESCENDING )
266 // if the chosen sort key is identical, sort by index
267 // (makes this a stable sort, so that later replies from servers won't
268 // shuffle the servers around when they have the same ping)
272 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
274 // This should actually be done with some intermediate and end-of-function return
286 case SLMO_GREATEREQUAL:
288 case SLMO_NOTCONTAIN:
289 case SLMO_STARTSWITH:
290 case SLMO_NOTSTARTSWITH:
293 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
298 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
301 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
302 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
303 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
304 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
306 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
307 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
310 // Same here, also using an intermediate & final return would be more appropriate
314 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
315 case SLMO_NOTCONTAIN:
316 return !*bufferB || !strstr( bufferA, bufferB );
317 case SLMO_STARTSWITH:
318 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
319 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
320 case SLMO_NOTSTARTSWITH:
321 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
323 return strcmp( bufferA, bufferB ) < 0;
325 return strcmp( bufferA, bufferB ) <= 0;
327 return strcmp( bufferA, bufferB ) == 0;
329 return strcmp( bufferA, bufferB ) > 0;
331 return strcmp( bufferA, bufferB ) != 0;
332 case SLMO_GREATEREQUAL:
333 return strcmp( bufferA, bufferB ) >= 0;
335 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
340 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
342 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
344 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
346 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
348 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
350 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
352 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
354 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
356 if( *mask->info.cname
357 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
360 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
363 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
366 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
369 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
371 if( *mask->info.qcstatus
372 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
374 if( *mask->info.players
375 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
377 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
382 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
384 int start, end, mid, i;
387 // reject incompatible servers
389 entry->info.gameversion != gameversion.integer
392 gameversion_min.integer >= 0 // min/max range set by user/mod?
393 && gameversion_max.integer >= 0
394 && gameversion_min.integer >= entry->info.gameversion // version of server in min/max range?
395 && gameversion_max.integer <= entry->info.gameversion
400 // refresh the "favorite" status
401 entry->info.isfavorite = false;
402 if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
404 for(i = 0; i < nFavorites; ++i)
406 if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
408 entry->info.isfavorite = true;
414 // FIXME: change this to be more readable (...)
415 // now check whether it passes through the masks
416 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
417 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
420 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
421 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
423 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
426 if( !serverlist_viewcount ) {
427 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
430 // ok, insert it, we just need to find out where exactly:
433 // check whether to insert it as new first item
434 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(0) ) ) {
435 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
437 } // check whether to insert it as new last item
438 else if( !_ServerList_Entry_Compare( entry, ServerList_GetViewEntry(serverlist_viewcount - 1) ) ) {
439 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
443 end = serverlist_viewcount - 1;
444 while( end > start + 1 )
446 mid = (start + end) / 2;
447 // test the item that lies in the middle between start and end
448 if( _ServerList_Entry_Compare( entry, ServerList_GetViewEntry(mid) ) )
449 // the item has to be in the upper half
452 // the item has to be in the lower half
455 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
458 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
461 for( i = 0; i < serverlist_viewcount; i++ )
463 if (ServerList_GetViewEntry(i) == entry)
465 _ServerList_ViewList_Helper_Remove(i);
471 void ServerList_RebuildViewList(void)
475 serverlist_viewcount = 0;
476 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
477 serverlist_entry_t *entry = &serverlist_cache[i];
478 // also display entries that are currently being refreshed [11/8/2007 Black]
479 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
480 ServerList_ViewList_Insert( entry );
484 void ServerList_ResetMasks(void)
488 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
489 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
490 // numbots needs to be compared to -1 to always succeed
491 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
492 serverlist_andmasks[i].info.numbots = -1;
493 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
494 serverlist_ormasks[i].info.numbots = -1;
497 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
500 int numplayers = 0, maxplayers = 0;
501 for (i = 0;i < serverlist_cachecount;i++)
503 if (serverlist_cache[i].query == SQS_QUERIED)
505 numplayers += serverlist_cache[i].info.numhumans;
506 maxplayers += serverlist_cache[i].info.maxplayers;
509 *numplayerspointer = numplayers;
510 *maxplayerspointer = maxplayers;
514 static void _ServerList_Test(void)
517 if (serverlist_maxcachecount <= 1024)
519 serverlist_maxcachecount = 1024;
520 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
522 for( i = 0 ; i < 1024 ; i++ ) {
523 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
524 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
525 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
526 serverlist_cache[serverlist_cachecount].finished = true;
527 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 );
528 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
529 serverlist_cachecount++;
534 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
536 masterquerytime = realtime;
537 masterquerycount = 0;
538 masterreplycount = 0;
540 serverquerycount = 0;
541 serverreplycount = 0;
542 serverlist_cachecount = 0;
543 serverlist_viewcount = 0;
544 serverlist_maxcachecount = 0;
545 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
547 // refresh all entries
549 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
550 serverlist_entry_t *entry = &serverlist_cache[ n ];
551 entry->query = SQS_REFRESHING;
552 entry->querycounter = 0;
555 serverlist_consoleoutput = consoleoutput;
557 //_ServerList_Test();
559 NetConn_QueryMasters(querydp, queryqw);
564 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
566 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
570 if (cl_netpacketloss_receive.integer)
571 for (i = 0;i < cl_numsockets;i++)
572 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
574 if (developer_networking.integer)
576 char addressstring[128], addressstring2[128];
577 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
580 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
581 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
582 Com_HexDumpToConsole((unsigned char *)data, length);
585 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
590 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
594 if (cl_netpacketloss_send.integer)
595 for (i = 0;i < cl_numsockets;i++)
596 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
598 ret = LHNET_Write(mysocket, data, length, peeraddress);
599 if (developer_networking.integer)
601 char addressstring[128], addressstring2[128];
602 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
603 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
604 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)");
605 Com_HexDumpToConsole((unsigned char *)data, length);
610 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
612 // note this does not include the trailing NULL because we add that in the parser
613 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
616 qboolean NetConn_CanSend(netconn_t *conn)
618 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
619 conn->outgoing_netgraph[conn->outgoing_packetcounter].time = realtime;
620 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
621 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
622 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes = NETGRAPH_NOPACKET;
623 if (realtime > conn->cleartime)
627 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_CHOKEDPACKET;
632 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
636 // if this packet was supposedly choked, but we find ourselves sending one
637 // anyway, make sure the size counting starts at zero
638 // (this mostly happens on level changes and disconnects and such)
639 if (conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes == NETGRAPH_CHOKEDPACKET)
640 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
642 if (protocol == PROTOCOL_QUAKEWORLD)
645 qboolean sendreliable;
647 // note that it is ok to send empty messages to the qw server,
648 // otherwise it won't respond to us at all
650 sendreliable = false;
651 // if the remote side dropped the last reliable message, resend it
652 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
654 // if the reliable transmit buffer is empty, copy the current message out
655 if (!conn->sendMessageLength && conn->message.cursize)
657 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
658 conn->sendMessageLength = conn->message.cursize;
659 SZ_Clear(&conn->message); // clear the message buffer
660 conn->qw.reliable_sequence ^= 1;
663 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
664 StoreLittleLong(sendbuffer, (unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
665 // last received unreliable packet number, and last received reliable packet number (0 or 1)
666 StoreLittleLong(sendbuffer + 4, (unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
668 conn->outgoing_unreliable_sequence++;
669 // client sends qport in every packet
670 if (conn == cls.netcon)
672 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
674 // also update cls.qw_outgoing_sequence
675 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
677 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
679 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
683 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
685 // add the reliable message if there is one
688 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += conn->sendMessageLength + 28;
689 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
690 packetLen += conn->sendMessageLength;
691 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
694 // add the unreliable message if possible
695 if (packetLen + data->cursize <= 1400)
697 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += data->cursize + 28;
698 memcpy(sendbuffer + packetLen, data->data, data->cursize);
699 packetLen += data->cursize;
702 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
705 unreliableMessagesSent++;
707 totallen += packetLen + 28;
711 unsigned int packetLen;
712 unsigned int dataLen;
715 // if a reliable message fragment has been lost, send it again
716 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
718 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
720 dataLen = conn->sendMessageLength;
725 dataLen = MAX_PACKETFRAGMENT;
729 packetLen = NET_HEADERSIZE + dataLen;
731 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
732 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence - 1);
733 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
735 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
737 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
739 conn->lastSendTime = realtime;
743 totallen += packetLen + 28;
746 // if we have a new reliable message to send, do so
747 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
749 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
751 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
752 conn->message.overflowed = true;
756 if (developer_networking.integer && conn == cls.netcon)
758 Con_Print("client sending reliable message to server:\n");
759 SZ_HexDumpToConsole(&conn->message);
762 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
763 conn->sendMessageLength = conn->message.cursize;
764 SZ_Clear(&conn->message);
766 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
768 dataLen = conn->sendMessageLength;
773 dataLen = MAX_PACKETFRAGMENT;
777 packetLen = NET_HEADERSIZE + dataLen;
779 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
780 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
781 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
783 conn->nq.sendSequence++;
785 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
787 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
789 conn->lastSendTime = realtime;
791 reliableMessagesSent++;
793 totallen += packetLen + 28;
796 // if we have an unreliable message to send, do so
799 packetLen = NET_HEADERSIZE + data->cursize;
801 if (packetLen > (int)sizeof(sendbuffer))
803 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
807 StoreBigLong(sendbuffer, packetLen | NETFLAG_UNRELIABLE);
808 StoreBigLong(sendbuffer + 4, conn->outgoing_unreliable_sequence);
809 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
811 conn->outgoing_unreliable_sequence++;
813 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
815 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
818 unreliableMessagesSent++;
820 totallen += packetLen + 28;
824 // delay later packets to obey rate limit
825 if (conn->cleartime < realtime - 0.1)
826 conn->cleartime = realtime - 0.1;
827 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
828 if (conn->cleartime < realtime)
829 conn->cleartime = realtime;
834 qboolean NetConn_HaveClientPorts(void)
836 return !!cl_numsockets;
839 qboolean NetConn_HaveServerPorts(void)
841 return !!sv_numsockets;
844 void NetConn_CloseClientPorts(void)
846 for (;cl_numsockets > 0;cl_numsockets--)
847 if (cl_sockets[cl_numsockets - 1])
848 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
851 void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
853 lhnetaddress_t address;
856 char addressstring2[1024];
857 if (addressstring && addressstring[0])
858 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
860 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
863 if ((s = LHNET_OpenSocket_Connectionless(&address)))
865 cl_sockets[cl_numsockets++] = s;
866 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
867 if (addresstype != LHNETADDRESSTYPE_LOOP)
868 Con_Printf("Client opened a socket on address %s\n", addressstring2);
872 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
873 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
877 Con_Printf("Client unable to parse address %s\n", addressstring);
880 void NetConn_OpenClientPorts(void)
883 NetConn_CloseClientPorts();
884 port = bound(0, cl_netport.integer, 65535);
885 if (cl_netport.integer != port)
886 Cvar_SetValueQuick(&cl_netport, port);
888 Con_Printf("Client using an automatically assigned port\n");
890 Con_Printf("Client using port %i\n", port);
891 NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
892 NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
894 NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
898 void NetConn_CloseServerPorts(void)
900 for (;sv_numsockets > 0;sv_numsockets--)
901 if (sv_sockets[sv_numsockets - 1])
902 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
905 qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
907 lhnetaddress_t address;
910 char addressstring2[1024];
913 for (port = defaultport; port <= defaultport + range; port++)
915 if (addressstring && addressstring[0])
916 success = LHNETADDRESS_FromString(&address, addressstring, port);
918 success = LHNETADDRESS_FromPort(&address, addresstype, port);
921 if ((s = LHNET_OpenSocket_Connectionless(&address)))
923 sv_sockets[sv_numsockets++] = s;
924 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
925 if (addresstype != LHNETADDRESSTYPE_LOOP)
926 Con_Printf("Server listening on address %s\n", addressstring2);
931 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
932 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
937 Con_Printf("Server unable to parse address %s\n", addressstring);
938 // if it cant parse one address, it wont be able to parse another for sure
945 void NetConn_OpenServerPorts(int opennetports)
948 NetConn_CloseServerPorts();
949 NetConn_UpdateSockets();
950 port = bound(0, sv_netport.integer, 65535);
953 Con_Printf("Server using port %i\n", port);
954 if (sv_netport.integer != port)
955 Cvar_SetValueQuick(&sv_netport, port);
956 if (cls.state != ca_dedicated)
957 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
961 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
962 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
964 NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
967 if (sv_numsockets == 0)
968 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
971 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
973 int i, a = LHNETADDRESS_GetAddressType(address);
974 for (i = 0;i < cl_numsockets;i++)
975 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
976 return cl_sockets[i];
980 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
982 int i, a = LHNETADDRESS_GetAddressType(address);
983 for (i = 0;i < sv_numsockets;i++)
984 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
985 return sv_sockets[i];
989 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
992 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
993 conn->mysocket = mysocket;
994 conn->peeraddress = *peeraddress;
995 conn->lastMessageTime = realtime;
996 conn->message.data = conn->messagedata;
997 conn->message.maxsize = sizeof(conn->messagedata);
998 conn->message.cursize = 0;
999 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
1000 // reduce effectiveness of connection request floods
1001 conn->timeout = realtime + net_connecttimeout.value;
1002 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
1003 conn->next = netconn_list;
1004 netconn_list = conn;
1008 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
1009 void NetConn_Close(netconn_t *conn)
1012 // remove connection from list
1014 // allow the client to reconnect immediately
1015 NetConn_ClearConnectFlood(&(conn->peeraddress));
1017 if (conn == netconn_list)
1018 netconn_list = conn->next;
1021 for (c = netconn_list;c;c = c->next)
1023 if (c->next == conn)
1025 c->next = conn->next;
1029 // not found in list, we'll avoid crashing here...
1037 static int clientport = -1;
1038 static int clientport2 = -1;
1039 static int hostport = -1;
1040 void NetConn_UpdateSockets(void)
1044 if (cls.state != ca_dedicated)
1046 if (clientport2 != cl_netport.integer)
1048 clientport2 = cl_netport.integer;
1049 if (cls.state == ca_connected)
1050 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1052 if (cls.state == ca_disconnected && clientport != clientport2)
1054 clientport = clientport2;
1055 NetConn_CloseClientPorts();
1057 if (cl_numsockets == 0)
1058 NetConn_OpenClientPorts();
1061 if (hostport != sv_netport.integer)
1063 hostport = sv_netport.integer;
1065 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1068 for (j = 0;j < MAX_RCONS;j++)
1070 i = (cls.rcon_ringpos + j + 1) % MAX_RCONS;
1071 if(cls.rcon_commands[i][0])
1073 if(realtime > cls.rcon_timeout[i])
1076 LHNETADDRESS_ToString(&cls.rcon_addresses[i], s, sizeof(s), true);
1077 Con_Printf("rcon to %s (for command %s) failed: challenge request timed out\n", s, cls.rcon_commands[i]);
1078 cls.rcon_commands[i][0] = 0;
1086 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1088 int originallength = length;
1092 if (protocol == PROTOCOL_QUAKEWORLD)
1094 int sequence, sequence_ack;
1095 int reliable_ack, reliable_message;
1099 sequence = LittleLong(*((int *)(data + 0)));
1100 sequence_ack = LittleLong(*((int *)(data + 4)));
1104 if (conn != cls.netcon)
1109 // 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?)
1110 //qport = LittleShort(*((int *)(data + 8)));
1116 reliable_message = (sequence >> 31) & 1;
1117 reliable_ack = (sequence_ack >> 31) & 1;
1118 sequence &= ~(1<<31);
1119 sequence_ack &= ~(1<<31);
1120 if (sequence <= conn->qw.incoming_sequence)
1122 //Con_DPrint("Got a stale datagram\n");
1125 count = sequence - (conn->qw.incoming_sequence + 1);
1128 droppedDatagrams += count;
1129 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1132 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1133 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1134 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1135 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1136 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1139 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1140 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1141 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1142 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1143 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1144 if (reliable_ack == conn->qw.reliable_sequence)
1146 // received, now we will be able to send another reliable message
1147 conn->sendMessageLength = 0;
1148 reliableMessagesReceived++;
1150 conn->qw.incoming_sequence = sequence;
1151 if (conn == cls.netcon)
1152 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1153 conn->qw.incoming_acknowledged = sequence_ack;
1154 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1155 if (reliable_message)
1156 conn->qw.incoming_reliable_sequence ^= 1;
1157 conn->lastMessageTime = realtime;
1158 conn->timeout = realtime + newtimeout;
1159 unreliableMessagesReceived++;
1160 SZ_Clear(&net_message);
1161 SZ_Write(&net_message, data, length);
1169 unsigned int sequence;
1172 qlength = (unsigned int)BuffBigLong(data);
1173 flags = qlength & ~NETFLAG_LENGTH_MASK;
1174 qlength &= NETFLAG_LENGTH_MASK;
1175 // control packets were already handled
1176 if (!(flags & NETFLAG_CTL) && qlength == length)
1178 sequence = BuffBigLong(data + 4);
1182 if (flags & NETFLAG_UNRELIABLE)
1184 if (sequence >= conn->nq.unreliableReceiveSequence)
1186 if (sequence > conn->nq.unreliableReceiveSequence)
1188 count = sequence - conn->nq.unreliableReceiveSequence;
1189 droppedDatagrams += count;
1190 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1193 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1194 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1195 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1196 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1197 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1200 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1201 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1202 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1203 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1204 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1205 conn->nq.unreliableReceiveSequence = sequence + 1;
1206 conn->lastMessageTime = realtime;
1207 conn->timeout = realtime + newtimeout;
1208 unreliableMessagesReceived++;
1211 SZ_Clear(&net_message);
1212 SZ_Write(&net_message, data, length);
1218 // Con_DPrint("Got a stale datagram\n");
1221 else if (flags & NETFLAG_ACK)
1223 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1224 if (sequence == (conn->nq.sendSequence - 1))
1226 if (sequence == conn->nq.ackSequence)
1228 conn->nq.ackSequence++;
1229 if (conn->nq.ackSequence != conn->nq.sendSequence)
1230 Con_DPrint("ack sequencing error\n");
1231 conn->lastMessageTime = realtime;
1232 conn->timeout = realtime + newtimeout;
1233 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1235 unsigned int packetLen;
1236 unsigned int dataLen;
1239 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1240 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1242 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1244 dataLen = conn->sendMessageLength;
1249 dataLen = MAX_PACKETFRAGMENT;
1253 packetLen = NET_HEADERSIZE + dataLen;
1255 StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
1256 StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
1257 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1259 conn->nq.sendSequence++;
1261 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1263 conn->lastSendTime = realtime;
1268 conn->sendMessageLength = 0;
1271 // Con_DPrint("Duplicate ACK received\n");
1274 // Con_DPrint("Stale ACK received\n");
1277 else if (flags & NETFLAG_DATA)
1279 unsigned char temppacket[8];
1280 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes += originallength + 28;
1281 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes += 8 + 28;
1282 StoreBigLong(temppacket, 8 | NETFLAG_ACK);
1283 StoreBigLong(temppacket + 4, sequence);
1284 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1285 if (sequence == conn->nq.receiveSequence)
1287 conn->lastMessageTime = realtime;
1288 conn->timeout = realtime + newtimeout;
1289 conn->nq.receiveSequence++;
1290 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1291 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1292 conn->receiveMessageLength += length;
1294 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1295 "Dropping the message!\n", sequence );
1296 conn->receiveMessageLength = 0;
1299 if (flags & NETFLAG_EOM)
1301 reliableMessagesReceived++;
1302 length = conn->receiveMessageLength;
1303 conn->receiveMessageLength = 0;
1306 SZ_Clear(&net_message);
1307 SZ_Write(&net_message, conn->receiveMessage, length);
1314 receivedDuplicateCount++;
1322 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1324 cls.connect_trying = false;
1325 M_Update_Return_Reason("");
1326 // the connection request succeeded, stop current connection and set up a new connection
1328 // if we're connecting to a remote server, shut down any local server
1329 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1330 Host_ShutdownServer ();
1331 // allocate a net connection to keep track of things
1332 cls.netcon = NetConn_Open(mysocket, peeraddress);
1333 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1334 key_dest = key_game;
1336 cls.demonum = -1; // not in the demo loop now
1337 cls.state = ca_connected;
1338 cls.signon = 0; // need all the signon messages before playing
1339 cls.protocol = initialprotocol;
1340 // reset move sequence numbering on this new connection
1341 cls.servermovesequence = 0;
1342 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1343 Cmd_ForwardStringToServer("new");
1344 if (cls.protocol == PROTOCOL_QUAKE)
1346 // write a keepalive (clc_nop) as it seems to greatly improve the
1347 // chances of connecting to a netquake server
1349 unsigned char buf[4];
1350 memset(&msg, 0, sizeof(msg));
1352 msg.maxsize = sizeof(buf);
1353 MSG_WriteChar(&msg, clc_nop);
1354 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1358 int NetConn_IsLocalGame(void)
1360 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1365 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1369 serverlist_entry_t *entry = NULL;
1371 // search the cache for this server and update it
1372 for (n = 0;n < serverlist_cachecount;n++) {
1373 entry = &serverlist_cache[ n ];
1374 if (!strcmp(addressstring, entry->info.cname))
1378 if (n == serverlist_cachecount)
1380 // LAN search doesnt require an answer from the master server so we wont
1381 // know the ping nor will it be initialized already...
1384 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1387 if (serverlist_maxcachecount <= serverlist_cachecount)
1389 serverlist_maxcachecount += 64;
1390 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1392 entry = &serverlist_cache[n];
1394 memset(entry, 0, sizeof(*entry));
1395 // store the data the engine cares about (address and ping)
1396 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1397 entry->info.ping = 100000;
1398 entry->querytime = realtime;
1399 // if not in the slist menu we should print the server to console
1400 if (serverlist_consoleoutput)
1401 Con_Printf("querying %s\n", addressstring);
1402 ++serverlist_cachecount;
1404 // if this is the first reply from this server, count it as having replied
1405 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1406 pingtime = bound(0, pingtime, 9999);
1407 if (entry->query == SQS_REFRESHING) {
1408 entry->info.ping = pingtime;
1409 entry->query = SQS_QUERIED;
1411 // convert to unsigned to catch the -1
1412 // 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]
1413 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1417 // other server info is updated by the caller
1421 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1423 serverlist_entry_t *entry = &serverlist_cache[n];
1424 serverlist_info_t *info = &entry->info;
1425 // update description strings for engine menu and console output
1426 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);
1427 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1429 info->gameversion != gameversion.integer
1432 gameversion_min.integer >= 0 // min/max range set by user/mod?
1433 && gameversion_max.integer >= 0
1434 && gameversion_min.integer >= info->gameversion // version of server in min/max range?
1435 && gameversion_max.integer <= info->gameversion
1438 info->mod, info->map);
1439 if (entry->query == SQS_QUERIED)
1441 if(!serverlist_paused)
1442 ServerList_ViewList_Remove(entry);
1444 // if not in the slist menu we should print the server to console (if wanted)
1445 else if( serverlist_consoleoutput )
1446 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1447 // and finally, update the view set
1448 if(!serverlist_paused)
1449 ServerList_ViewList_Insert( entry );
1450 // update the entry's state
1451 serverlist_cache[n].query = SQS_QUERIED;
1454 // returns true, if it's sensible to continue the processing
1455 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1457 serverlist_entry_t *entry;
1459 // ignore the rest of the message if the serverlist is full
1460 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1462 // also ignore it if we have already queried it (other master server response)
1463 for( n = 0 ; n < serverlist_cachecount ; n++ )
1464 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1467 if( n < serverlist_cachecount ) {
1468 // the entry has already been queried once or
1472 if (serverlist_maxcachecount <= n)
1474 serverlist_maxcachecount += 64;
1475 serverlist_cache = (serverlist_entry_t *)Mem_Realloc(netconn_mempool, (void *)serverlist_cache, sizeof(serverlist_entry_t) * serverlist_maxcachecount);
1478 entry = &serverlist_cache[n];
1480 memset(entry, 0, sizeof(entry));
1481 entry->protocol = protocol;
1482 // store the data the engine cares about (address and ping)
1483 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1485 entry->info.isfavorite = isfavorite;
1487 // no, then reset the ping right away
1488 entry->info.ping = -1;
1489 // we also want to increase the serverlist_cachecount then
1490 serverlist_cachecount++;
1493 entry->query = SQS_QUERYING;
1498 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1501 if (serverlist_consoleoutput)
1502 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1505 char ipstring [128];
1508 if (data[0] == '\\')
1510 unsigned short port = data[5] * 256 + data[6];
1512 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1513 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1515 // move on to next address in packet
1520 else if (data[0] == '/' && isextended && length >= 19)
1522 unsigned short port = data[17] * 256 + data[18];
1528 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1530 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1533 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1534 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1535 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1540 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1541 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1542 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1547 // move on to next address in packet
1553 Con_Print("Error while parsing the server list\n");
1557 if (serverlist_consoleoutput && developer_networking.integer)
1558 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1560 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1566 // begin or resume serverlist queries
1567 serverlist_querysleep = false;
1568 serverlist_querywaittime = realtime + 3;
1571 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1573 qboolean fromserver;
1574 int ret, c, control;
1576 char *string, addressstring2[128], ipstring[32];
1577 char stringbuf[16384];
1579 // quakeworld ingame packet
1580 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1582 // convert the address to a string incase we need it
1583 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1585 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1587 // received a command string - strip off the packaging and put it
1588 // into our string buffer with NULL termination
1591 length = min(length, (int)sizeof(stringbuf) - 1);
1592 memcpy(stringbuf, data, length);
1593 stringbuf[length] = 0;
1596 if (developer_networking.integer)
1598 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1599 Com_HexDumpToConsole(data, length);
1602 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1605 for (j = 0;j < MAX_RCONS;j++)
1607 // note: this value from i is used outside the loop too...
1608 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1609 if(cls.rcon_commands[i][0])
1610 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1619 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1620 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1622 e = strchr(rcon_password.string, ' ');
1623 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1625 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1629 strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1630 NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1631 cls.rcon_commands[i][0] = 0;
1634 for (k = 0;k < MAX_RCONS;k++)
1635 if(cls.rcon_commands[k][0])
1636 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[k]))
1641 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1642 // extend the timeout on other requests as we asked for a challenge
1643 for (l = 0;l < MAX_RCONS;l++)
1644 if(cls.rcon_commands[l][0])
1645 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[l]))
1646 cls.rcon_timeout[l] = realtime + rcon_secure_challengetimeout.value;
1649 return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1653 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1655 // darkplaces or quake3
1656 char protocolnames[1400];
1657 Protocol_Names(protocolnames, sizeof(protocolnames));
1658 Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1659 M_Update_Return_Reason("Got challenge response");
1660 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1661 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1662 // TODO: add userinfo stuff here instead of using NQ commands?
1663 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s%s\\challenge\\%s", protocolnames, cls.connect_userinfo, string + 10), peeraddress);
1666 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1668 // darkplaces or quake3
1669 M_Update_Return_Reason("Accepted");
1670 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1673 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1675 char rejectreason[32];
1676 cls.connect_trying = false;
1678 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1679 memcpy(rejectreason, string, length);
1680 rejectreason[length] = 0;
1681 M_Update_Return_Reason(rejectreason);
1684 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1686 serverlist_info_t *info;
1691 // search the cache for this server and update it
1692 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1696 info = &serverlist_cache[n].info;
1701 info->qcstatus[0] = 0;
1702 info->players[0] = 0;
1703 info->protocol = -1;
1704 info->numplayers = 0;
1706 info->maxplayers = 0;
1707 info->gameversion = 0;
1709 p = strchr(string, '\n');
1712 *p = 0; // cut off the string there
1716 Con_Printf("statusResponse without players block?\n");
1718 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1719 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1720 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1721 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1722 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1723 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1724 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1725 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1726 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1727 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1728 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1729 info->numhumans = info->numplayers - max(0, info->numbots);
1730 info->freeslots = info->maxplayers - info->numplayers;
1732 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1736 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1738 serverlist_info_t *info;
1742 // search the cache for this server and update it
1743 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1747 info = &serverlist_cache[n].info;
1752 info->qcstatus[0] = 0;
1753 info->players[0] = 0;
1754 info->protocol = -1;
1755 info->numplayers = 0;
1757 info->maxplayers = 0;
1758 info->gameversion = 0;
1760 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1761 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1762 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1763 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1764 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1765 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1766 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1767 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1768 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1769 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1770 info->numhumans = info->numplayers - max(0, info->numbots);
1771 info->freeslots = info->maxplayers - info->numplayers;
1773 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1777 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1779 // Extract the IP addresses
1782 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1785 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1787 // Extract the IP addresses
1790 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1793 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1795 // Extract the IP addresses
1799 if (serverlist_consoleoutput)
1800 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1801 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1803 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1804 if (serverlist_consoleoutput && developer_networking.integer)
1805 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1807 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1811 // move on to next address in packet
1815 // begin or resume serverlist queries
1816 serverlist_querysleep = false;
1817 serverlist_querywaittime = realtime + 3;
1820 if (!strncmp(string, "extResponse ", 12))
1822 ++cl_net_extresponse_count;
1823 if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1824 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1825 cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1826 dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1829 if (!strncmp(string, "ping", 4))
1831 if (developer_extra.integer)
1832 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1833 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1836 if (!strncmp(string, "ack", 3))
1838 // QuakeWorld compatibility
1839 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1841 // challenge message
1842 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1843 M_Update_Return_Reason("Got QuakeWorld challenge response");
1844 cls.qw_qport = qport.integer;
1845 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1846 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1847 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);
1850 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1853 M_Update_Return_Reason("QuakeWorld Accepted");
1854 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1857 if (length > 2 && !memcmp(string, "n\\", 2))
1859 serverlist_info_t *info;
1863 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1864 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1867 // search the cache for this server and update it
1868 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1872 info = &serverlist_cache[n].info;
1873 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1874 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1875 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1876 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1878 info->numplayers = 0; // updated below
1879 info->numhumans = 0; // updated below
1880 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1881 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1883 // count active players on server
1884 // (we could gather more info, but we're just after the number)
1885 s = strchr(string, '\n');
1889 while (s < string + length)
1891 for (;s < string + length && *s != '\n';s++)
1893 if (s >= string + length)
1901 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1905 if (string[0] == 'n')
1908 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1910 // we may not have liked the packet, but it was a command packet, so
1911 // we're done processing this packet now
1914 // quakeworld ingame packet
1915 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1918 CL_ParseServerMessage();
1921 // netquake control packets, supported for compatibility only
1922 if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1925 serverlist_info_t *info;
1929 SZ_Clear(&net_message);
1930 SZ_Write(&net_message, data, length);
1936 if (developer_extra.integer)
1937 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1938 if (cls.connect_trying)
1940 lhnetaddress_t clientportaddress;
1941 clientportaddress = *peeraddress;
1942 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
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 M_Update_Return_Reason("Accepted");
1946 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1950 if (developer_extra.integer)
1951 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1952 cls.connect_trying = false;
1953 M_Update_Return_Reason((char *)MSG_ReadString());
1955 case CCREP_SERVER_INFO:
1956 if (developer_extra.integer)
1957 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1958 // LordHavoc: because the quake server may report weird addresses
1959 // we just ignore it and keep the real address
1961 // search the cache for this server and update it
1962 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1966 info = &serverlist_cache[n].info;
1967 strlcpy(info->game, "Quake", sizeof(info->game));
1968 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1969 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1970 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1971 info->numplayers = MSG_ReadByte();
1972 info->maxplayers = MSG_ReadByte();
1973 info->protocol = MSG_ReadByte();
1975 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1978 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1979 if (developer_extra.integer)
1980 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1982 Con_Printf("%s\n", MSG_ReadString());
1984 case CCREP_PLAYER_INFO:
1985 // we got a CCREP_PLAYER_INFO??
1986 //if (developer_extra.integer)
1987 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1989 case CCREP_RULE_INFO:
1990 // we got a CCREP_RULE_INFO??
1991 //if (developer_extra.integer)
1992 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1997 SZ_Clear(&net_message);
1998 // we may not have liked the packet, but it was a valid control
1999 // packet, so we're done processing this packet now
2003 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2004 CL_ParseServerMessage();
2008 void NetConn_QueryQueueFrame(void)
2014 static double querycounter = 0;
2016 if(!net_slist_pause.integer && serverlist_paused)
2017 ServerList_RebuildViewList();
2018 serverlist_paused = net_slist_pause.integer != 0;
2020 if (serverlist_querysleep)
2023 // apply a cool down time after master server replies,
2024 // to avoid messing up the ping times on the servers
2025 if (serverlist_querywaittime > realtime)
2028 // each time querycounter reaches 1.0 issue a query
2029 querycounter += cl.realframetime * net_slist_queriespersecond.value;
2030 maxqueries = (int)querycounter;
2031 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2032 querycounter -= maxqueries;
2034 if( maxqueries == 0 ) {
2038 // scan serverlist and issue queries as needed
2039 serverlist_querysleep = true;
2041 timeouttime = realtime - net_slist_timeout.value;
2042 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
2044 serverlist_entry_t *entry = &serverlist_cache[ index ];
2045 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2050 serverlist_querysleep = false;
2051 if( entry->querycounter != 0 && entry->querytime > timeouttime )
2056 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
2058 lhnetaddress_t address;
2061 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2062 if (entry->protocol == PROTOCOL_QUAKEWORLD)
2064 for (socket = 0; socket < cl_numsockets ; socket++)
2065 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2069 for (socket = 0; socket < cl_numsockets ; socket++)
2070 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2073 // update the entry fields
2074 entry->querytime = realtime;
2075 entry->querycounter++;
2077 // if not in the slist menu we should print the server to console
2078 if (serverlist_consoleoutput)
2079 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2085 // have we tried to refresh this server?
2086 if( entry->query == SQS_REFRESHING ) {
2087 // yes, so update the reply count (since its not responding anymore)
2089 if(!serverlist_paused)
2090 ServerList_ViewList_Remove(entry);
2092 entry->query = SQS_TIMEDOUT;
2097 void NetConn_ClientFrame(void)
2100 lhnetaddress_t peeraddress;
2101 NetConn_UpdateSockets();
2102 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2104 if (cls.connect_remainingtries == 0)
2105 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2106 cls.connect_nextsendtime = realtime + 1;
2107 cls.connect_remainingtries--;
2108 if (cls.connect_remainingtries <= -10)
2110 cls.connect_trying = false;
2111 M_Update_Return_Reason("Connect: Failed");
2114 // try challenge first (newer DP server or QW)
2115 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2116 // then try netquake as a fallback (old server, or netquake)
2117 SZ_Clear(&net_message);
2118 // save space for the header, filled in later
2119 MSG_WriteLong(&net_message, 0);
2120 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2121 MSG_WriteString(&net_message, "QUAKE");
2122 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2123 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2124 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2125 SZ_Clear(&net_message);
2127 for (i = 0;i < cl_numsockets;i++)
2129 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2131 // R_TimeReport("clientreadnetwork");
2132 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2133 // R_TimeReport("clientparsepacket");
2136 NetConn_QueryQueueFrame();
2137 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2139 Con_Print("Connection timed out\n");
2141 Host_ShutdownServer ();
2145 #define MAX_CHALLENGES 128
2148 lhnetaddress_t address;
2152 challenge[MAX_CHALLENGES];
2154 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2158 for (i = 0;i < bufferlength - 1;i++)
2162 c = rand () % (127 - 33) + 33;
2163 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2169 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2170 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2173 unsigned int nb_clients = 0, nb_bots = 0, i;
2179 // How many clients are there?
2180 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2182 if (svs.clients[i].active)
2185 if (!svs.clients[i].netconnection)
2191 if(prog->globaloffsets.worldstatus >= 0)
2193 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2199 for(q = str; *q; ++q)
2200 if(*q != '\\' && *q != '\n')
2206 /// \TODO: we should add more information for the full status string
2207 length = dpsnprintf(out_msg, out_size,
2208 "\377\377\377\377%s\x0A"
2209 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2210 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2214 fullstatus ? "statusResponse" : "infoResponse",
2215 gamename, com_modname, gameversion.integer, svs.maxclients,
2216 nb_clients, nb_bots, sv.worldbasename, hostname.string, NET_PROTOCOL_VERSION,
2217 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2218 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2219 fullstatus ? "\n" : "");
2221 // Make sure it fits in the buffer
2231 savelength = length;
2233 ptr = out_msg + length;
2234 left = (int)out_size - length;
2236 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2238 client_t *cl = &svs.clients[i];
2241 int nameind, cleanind, pingvalue;
2243 char cleanname [sizeof(cl->name)];
2245 // Remove all characters '"' and '\' in the player name
2250 curchar = cl->name[nameind++];
2251 if (curchar != '"' && curchar != '\\')
2253 cleanname[cleanind++] = curchar;
2254 if (cleanind == sizeof(cleanname) - 1)
2257 } while (curchar != '\0');
2258 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2260 pingvalue = (int)(cl->ping * 1000.0f);
2261 if(cl->netconnection)
2262 pingvalue = bound(1, pingvalue, 9999);
2267 if(prog->fieldoffsets.clientstatus >= 0)
2269 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2275 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2276 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2282 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2284 if(cl->frags == -666) // spectator
2285 strlcpy(teambuf, " 0", sizeof(teambuf));
2286 else if(cl->colors == 0x44) // red team
2287 strlcpy(teambuf, " 1", sizeof(teambuf));
2288 else if(cl->colors == 0xDD) // blue team
2289 strlcpy(teambuf, " 2", sizeof(teambuf));
2290 else if(cl->colors == 0xCC) // yellow team
2291 strlcpy(teambuf, " 3", sizeof(teambuf));
2292 else if(cl->colors == 0x99) // pink team
2293 strlcpy(teambuf, " 4", sizeof(teambuf));
2295 strlcpy(teambuf, " 0", sizeof(teambuf));
2300 // note: team number is inserted according to SoF2 protocol
2302 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2308 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2317 // turn it into an infoResponse!
2318 out_msg[savelength] = 0;
2319 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2320 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2337 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2339 int floodslotnum, bestfloodslotnum;
2340 double bestfloodtime;
2341 lhnetaddress_t noportpeeraddress;
2342 // see if this is a connect flood
2343 noportpeeraddress = *peeraddress;
2344 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2345 bestfloodslotnum = 0;
2346 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2347 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2349 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2351 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2352 bestfloodslotnum = floodslotnum;
2354 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2356 // this address matches an ongoing flood address
2357 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2359 // renew the ban on this address so it does not expire
2360 // until the flood has subsided
2361 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2362 //Con_Printf("Flood detected!\n");
2365 // the flood appears to have subsided, so allow this
2366 bestfloodslotnum = floodslotnum; // reuse the same slot
2370 // begin a new timeout on this address
2371 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2372 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2373 //Con_Printf("Flood detection initiated!\n");
2377 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2380 lhnetaddress_t noportpeeraddress;
2381 // see if this is a connect flood
2382 noportpeeraddress = *peeraddress;
2383 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2384 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2386 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2388 // this address matches an ongoing flood address
2390 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2391 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2392 //Con_Printf("Flood cleared!\n");
2397 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2399 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2404 t1 = (long) time(NULL);
2405 t2 = strtol(s, NULL, 0);
2406 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2409 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2412 return !memcmp(mdfourbuf, hash, 16);
2415 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2420 if(slen < (int)(sizeof(challenge[0].string)) - 1)
2423 // validate the challenge
2424 for (i = 0;i < MAX_CHALLENGES;i++)
2425 if(challenge[i].time > 0)
2426 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2428 // if the challenge is not recognized, drop the packet
2429 if (i == MAX_CHALLENGES)
2432 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2435 if(memcmp(mdfourbuf, hash, 16))
2438 // unmark challenge to prevent replay attacks
2439 challenge[i].time = 0;
2444 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2446 return !strcmp(password, hash);
2449 /// returns a string describing the user level, or NULL for auth failure
2450 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)
2452 const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2453 static char buf[MAX_INPUTLINE];
2455 qboolean restricted = false;
2456 qboolean have_usernames = false;
2458 userpass_start = rcon_password.string;
2459 while((userpass_end = strchr(userpass_start, ' ')))
2461 have_usernames = true;
2462 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2464 if(comparator(peeraddress, buf, password, cs, cslen))
2466 userpass_start = userpass_end + 1;
2468 if(userpass_start[0])
2470 userpass_end = userpass_start + strlen(userpass_start);
2471 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2476 have_usernames = false;
2477 userpass_start = rcon_restricted_password.string;
2478 while((userpass_end = strchr(userpass_start, ' ')))
2480 have_usernames = true;
2481 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2483 if(comparator(peeraddress, buf, password, cs, cslen))
2485 userpass_start = userpass_end + 1;
2487 if(userpass_start[0])
2489 userpass_end = userpass_start + strlen(userpass_start);
2490 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2494 return NULL; // DENIED
2497 for(text = s; text != endpos; ++text)
2498 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2499 return NULL; // block possible exploits against the parser/alias expansion
2503 size_t l = strlen(s);
2506 hasquotes = (strchr(s, '"') != NULL);
2507 // sorry, we can't allow these substrings in wildcard expressions,
2508 // as they can mess with the argument counts
2509 text = rcon_restricted_commands.string;
2510 while(COM_ParseToken_Console(&text))
2512 // com_token now contains a pattern to check for...
2513 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2516 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2519 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2521 if(!strcmp(com_token, s))
2524 else // single-arg expression? must match the beginning of the command
2526 if(!strcmp(com_token, s))
2528 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2532 // if we got here, nothing matched!
2540 userpass_startpass = strchr(userpass_start, ':');
2541 if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2542 return va("%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2544 return va("%srcon", restricted ? "restricted " : "");
2547 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2551 // looks like a legitimate rcon command with the correct password
2552 const char *s_ptr = s;
2553 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2554 while(s_ptr != endpos)
2556 size_t l = strlen(s_ptr);
2558 Con_Printf(" %s;", s_ptr);
2563 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2564 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2567 size_t l = strlen(s);
2570 client_t *host_client_save = host_client;
2571 Cmd_ExecuteString(s, src_command);
2572 host_client = host_client_save;
2573 // in case it is a command that changes host_client (like restart)
2577 Con_Rcon_Redirect_End();
2581 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2585 extern void SV_SendServerinfo (client_t *client);
2586 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2588 int i, ret, clientnum, best;
2591 char *s, *string, response[1400], addressstring2[128];
2592 static char stringbuf[16384];
2593 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2598 // convert the address to a string incase we need it
2599 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2601 // see if we can identify the sender as a local player
2602 // (this is necessary for rcon to send a reliable reply if the client is
2603 // actually on the server, not sending remotely)
2604 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2605 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2607 if (i == svs.maxclients)
2610 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2612 // received a command string - strip off the packaging and put it
2613 // into our string buffer with NULL termination
2616 length = min(length, (int)sizeof(stringbuf) - 1);
2617 memcpy(stringbuf, data, length);
2618 stringbuf[length] = 0;
2621 if (developer_extra.integer)
2623 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2624 Com_HexDumpToConsole(data, length);
2627 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2629 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2631 if(challenge[i].time > 0)
2632 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2634 if (besttime > challenge[i].time)
2635 besttime = challenge[best = i].time;
2637 // if we did not find an exact match, choose the oldest and
2638 // update address and string
2639 if (i == MAX_CHALLENGES)
2642 challenge[i].address = *peeraddress;
2643 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2645 challenge[i].time = realtime;
2646 // send the challenge
2647 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2650 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2655 if (!(s = SearchInfostring(string, "challenge")))
2657 // validate the challenge
2658 for (i = 0;i < MAX_CHALLENGES;i++)
2659 if(challenge[i].time > 0)
2660 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2662 // if the challenge is not recognized, drop the packet
2663 if (i == MAX_CHALLENGES)
2666 // check engine protocol
2667 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2669 if (developer_extra.integer)
2670 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2671 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2675 // see if this is a duplicate connection request or a disconnected
2676 // client who is rejoining to the same client slot
2677 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2679 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2681 // this is a known client...
2682 if (client->spawned)
2684 // client crashed and is coming back,
2685 // keep their stuff intact
2686 if (developer_extra.integer)
2687 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2688 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2690 SV_SendServerinfo(client);
2695 // client is still trying to connect,
2696 // so we send a duplicate reply
2697 if (developer_extra.integer)
2698 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2699 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2705 if (NetConn_PreventConnectFlood(peeraddress))
2708 // find an empty client slot for this new client
2709 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2712 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2714 // allocated connection
2715 if (developer_extra.integer)
2716 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2717 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2718 // now set up the client
2720 SV_ConnectClient(clientnum, conn);
2722 NetConn_Heartbeat(1);
2727 // no empty slots found - server is full
2728 if (developer_extra.integer)
2729 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2730 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2734 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2736 const char *challenge = NULL;
2738 // If there was a challenge in the getinfo message
2739 if (length > 8 && string[7] == ' ')
2740 challenge = string + 8;
2742 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2744 if (developer_extra.integer)
2745 Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
2746 NetConn_WriteString(mysocket, response, peeraddress);
2750 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2752 const char *challenge = NULL;
2754 // If there was a challenge in the getinfo message
2755 if (length > 10 && string[9] == ' ')
2756 challenge = string + 10;
2758 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2760 if (developer_extra.integer)
2761 Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
2762 NetConn_WriteString(mysocket, response, peeraddress);
2766 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2768 char *password = string + 20;
2769 char *timeval = string + 37;
2770 char *s = strchr(timeval, ' ');
2771 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2772 const char *userlevel;
2774 if(rcon_secure.integer > 1)
2778 return true; // invalid packet
2781 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2782 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2785 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
2787 char *password = string + 25;
2788 char *challenge = string + 42;
2789 char *s = strchr(challenge, ' ');
2790 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2791 const char *userlevel;
2793 return true; // invalid packet
2796 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
2797 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2800 if (length >= 5 && !memcmp(string, "rcon ", 5))
2803 char *s = string + 5;
2804 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2807 if(rcon_secure.integer > 0)
2810 for (i = 0;!ISWHITESPACE(*s);s++)
2811 if (i < (int)sizeof(password) - 1)
2813 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2816 if (!ISWHITESPACE(password[0]))
2818 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
2819 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2823 if (!strncmp(string, "extResponse ", 12))
2825 ++sv_net_extresponse_count;
2826 if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
2827 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
2828 sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
2829 dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
2832 if (!strncmp(string, "ping", 4))
2834 if (developer_extra.integer)
2835 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
2836 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2839 if (!strncmp(string, "ack", 3))
2841 // we may not have liked the packet, but it was a command packet, so
2842 // we're done processing this packet now
2845 // netquake control packets, supported for compatibility only, and only
2846 // when running game protocols that are normally served via this connection
2848 // (this protects more modern protocols against being used for
2849 // Quake packet flood Denial Of Service attacks)
2850 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))
2854 const char *protocolname;
2857 SZ_Clear(&net_message);
2858 SZ_Write(&net_message, data, length);
2864 if (developer_extra.integer)
2865 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2866 if(!islocal && sv_public.integer <= -2)
2869 protocolname = MSG_ReadString();
2870 protocolnumber = MSG_ReadByte();
2871 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2873 if (developer_extra.integer)
2874 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2875 SZ_Clear(&net_message);
2876 // save space for the header, filled in later
2877 MSG_WriteLong(&net_message, 0);
2878 MSG_WriteByte(&net_message, CCREP_REJECT);
2879 MSG_WriteString(&net_message, "Incompatible version.\n");
2880 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2881 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2882 SZ_Clear(&net_message);
2886 // see if this connect request comes from a known client
2887 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2889 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2891 // this is either a duplicate connection request
2892 // or coming back from a timeout
2893 // (if so, keep their stuff intact)
2896 if (developer_extra.integer)
2897 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2898 SZ_Clear(&net_message);
2899 // save space for the header, filled in later
2900 MSG_WriteLong(&net_message, 0);
2901 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2902 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2903 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2904 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2905 SZ_Clear(&net_message);
2907 // if client is already spawned, re-send the
2908 // serverinfo message as they'll need it to play
2909 if (client->spawned)
2912 SV_SendServerinfo(client);
2919 // this is a new client, check for connection flood
2920 if (NetConn_PreventConnectFlood(peeraddress))
2923 // find a slot for the new client
2924 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2927 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2929 // connect to the client
2930 // everything is allocated, just fill in the details
2931 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2932 if (developer_extra.integer)
2933 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2934 // send back the info about the server connection
2935 SZ_Clear(&net_message);
2936 // save space for the header, filled in later
2937 MSG_WriteLong(&net_message, 0);
2938 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2939 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2940 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2941 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2942 SZ_Clear(&net_message);
2943 // now set up the client struct
2945 SV_ConnectClient(clientnum, conn);
2947 NetConn_Heartbeat(1);
2952 if (developer_extra.integer)
2953 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2954 // no room; try to let player know
2955 SZ_Clear(&net_message);
2956 // save space for the header, filled in later
2957 MSG_WriteLong(&net_message, 0);
2958 MSG_WriteByte(&net_message, CCREP_REJECT);
2959 MSG_WriteString(&net_message, "Server is full.\n");
2960 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2961 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2962 SZ_Clear(&net_message);
2964 case CCREQ_SERVER_INFO:
2965 if (developer_extra.integer)
2966 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2967 if(!islocal && sv_public.integer <= -1)
2969 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2972 char myaddressstring[128];
2973 if (developer_extra.integer)
2974 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2975 SZ_Clear(&net_message);
2976 // save space for the header, filled in later
2977 MSG_WriteLong(&net_message, 0);
2978 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2979 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2980 MSG_WriteString(&net_message, myaddressstring);
2981 MSG_WriteString(&net_message, hostname.string);
2982 MSG_WriteString(&net_message, sv.name);
2983 // How many clients are there?
2984 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2985 if (svs.clients[i].active)
2987 MSG_WriteByte(&net_message, numclients);
2988 MSG_WriteByte(&net_message, svs.maxclients);
2989 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2990 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2991 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2992 SZ_Clear(&net_message);
2995 case CCREQ_PLAYER_INFO:
2996 if (developer_extra.integer)
2997 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2998 if(!islocal && sv_public.integer <= -1)
3002 int playerNumber, activeNumber, clientNumber;
3005 playerNumber = MSG_ReadByte();
3007 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3008 if (client->active && ++activeNumber == playerNumber)
3010 if (clientNumber != svs.maxclients)
3012 SZ_Clear(&net_message);
3013 // save space for the header, filled in later
3014 MSG_WriteLong(&net_message, 0);
3015 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
3016 MSG_WriteByte(&net_message, playerNumber);
3017 MSG_WriteString(&net_message, client->name);
3018 MSG_WriteLong(&net_message, client->colors);
3019 MSG_WriteLong(&net_message, client->frags);
3020 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
3021 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
3022 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3023 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3024 SZ_Clear(&net_message);
3028 case CCREQ_RULE_INFO:
3029 if (developer_extra.integer)
3030 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3031 if(!islocal && sv_public.integer <= -1)
3038 // find the search start location
3039 prevCvarName = MSG_ReadString();
3040 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3042 // send the response
3043 SZ_Clear(&net_message);
3044 // save space for the header, filled in later
3045 MSG_WriteLong(&net_message, 0);
3046 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
3049 MSG_WriteString(&net_message, var->name);
3050 MSG_WriteString(&net_message, var->string);
3052 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3053 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3054 SZ_Clear(&net_message);
3060 SZ_Clear(&net_message);
3061 // we may not have liked the packet, but it was a valid control
3062 // packet, so we're done processing this packet now
3067 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3070 SV_ReadClientMessage();
3078 void NetConn_ServerFrame(void)
3081 lhnetaddress_t peeraddress;
3082 for (i = 0;i < sv_numsockets;i++)
3083 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3084 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3085 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3087 // never timeout loopback connections
3088 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3090 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3092 SV_DropClient(false);
3098 void NetConn_SleepMicroseconds(int microseconds)
3100 LHNET_SleepUntilPacket_Microseconds(microseconds);
3103 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3107 lhnetaddress_t masteraddress;
3108 lhnetaddress_t broadcastaddress;
3111 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3114 // 26000 is the default quake server port, servers on other ports will not
3116 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3117 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3121 for (i = 0;i < cl_numsockets;i++)
3125 const char *cmdname, *extraoptions;
3126 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3128 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3130 // search LAN for Quake servers
3131 SZ_Clear(&net_message);
3132 // save space for the header, filled in later
3133 MSG_WriteLong(&net_message, 0);
3134 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
3135 MSG_WriteString(&net_message, "QUAKE");
3136 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3137 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3138 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
3139 SZ_Clear(&net_message);
3141 // search LAN for DarkPlaces servers
3142 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3145 // build the getservers message to send to the dpmaster master servers
3146 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3148 cmdname = "getserversExt";
3149 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
3153 cmdname = "getservers";
3156 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3159 for (masternum = 0;sv_masters[masternum].name;masternum++)
3161 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3164 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3168 // search favorite servers
3169 for(j = 0; j < nFavorites; ++j)
3171 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3173 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3174 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3181 // only query QuakeWorld servers when the user wants to
3184 for (i = 0;i < cl_numsockets;i++)
3188 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3190 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3192 // search LAN for QuakeWorld servers
3193 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3195 // build the getservers message to send to the qwmaster master servers
3196 // note this has no -1 prefix, and the trailing nul byte is sent
3197 dpsnprintf(request, sizeof(request), "c\n");
3201 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3203 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3205 if (m_state != m_slist)
3207 char lookupstring[128];
3208 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3209 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3212 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3216 // search favorite servers
3217 for(j = 0; j < nFavorites; ++j)
3219 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3221 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3223 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3224 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3231 if (!masterquerycount)
3233 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3234 M_Update_Return_Reason("No network");
3238 void NetConn_Heartbeat(int priority)
3240 lhnetaddress_t masteraddress;
3242 lhnetsocket_t *mysocket;
3244 // if it's a state change (client connected), limit next heartbeat to no
3245 // more than 30 sec in the future
3246 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3247 nextheartbeattime = realtime + 30.0;
3249 // limit heartbeatperiod to 30 to 270 second range,
3250 // lower limit is to avoid abusing master servers with excess traffic,
3251 // upper limit is to avoid timing out on the master server (which uses
3253 if (sv_heartbeatperiod.value < 30)
3254 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3255 if (sv_heartbeatperiod.value > 270)
3256 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3258 // make advertising optional and don't advertise singleplayer games, and
3259 // only send a heartbeat as often as the admin wants
3260 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3262 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3263 for (masternum = 0;sv_masters[masternum].name;masternum++)
3264 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3265 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3269 static void Net_Heartbeat_f(void)
3272 NetConn_Heartbeat(2);
3274 Con_Print("No server running, can not heartbeat to master server.\n");
3277 void PrintStats(netconn_t *conn)
3279 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3280 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3282 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3285 void Net_Stats_f(void)
3288 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3289 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3290 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3291 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3292 Con_Printf("packetsSent = %i\n", packetsSent);
3293 Con_Printf("packetsReSent = %i\n", packetsReSent);
3294 Con_Printf("packetsReceived = %i\n", packetsReceived);
3295 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3296 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3297 Con_Print("connections =\n");
3298 for (conn = netconn_list;conn;conn = conn->next)
3302 void Net_Refresh_f(void)
3304 if (m_state != m_slist) {
3305 Con_Print("Sending new requests to master servers\n");
3306 ServerList_QueryList(false, true, false, true);
3307 Con_Print("Listening for replies...\n");
3309 ServerList_QueryList(false, true, false, false);
3312 void Net_Slist_f(void)
3314 ServerList_ResetMasks();
3315 serverlist_sortbyfield = SLIF_PING;
3316 serverlist_sortflags = 0;
3317 if (m_state != m_slist) {
3318 Con_Print("Sending requests to master servers\n");
3319 ServerList_QueryList(true, true, false, true);
3320 Con_Print("Listening for replies...\n");
3322 ServerList_QueryList(true, true, false, false);
3325 void Net_SlistQW_f(void)
3327 ServerList_ResetMasks();
3328 serverlist_sortbyfield = SLIF_PING;
3329 serverlist_sortflags = 0;
3330 if (m_state != m_slist) {
3331 Con_Print("Sending requests to master servers\n");
3332 ServerList_QueryList(true, false, true, true);
3333 serverlist_consoleoutput = true;
3334 Con_Print("Listening for replies...\n");
3336 ServerList_QueryList(true, false, true, false);
3339 void NetConn_Init(void)
3342 lhnetaddress_t tempaddress;
3343 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3344 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3345 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3346 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3347 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3348 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3349 Cvar_RegisterVariable(&rcon_restricted_password);
3350 Cvar_RegisterVariable(&rcon_restricted_commands);
3351 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3352 Cvar_RegisterVariable(&net_slist_queriespersecond);
3353 Cvar_RegisterVariable(&net_slist_queriesperframe);
3354 Cvar_RegisterVariable(&net_slist_timeout);
3355 Cvar_RegisterVariable(&net_slist_maxtries);
3356 Cvar_RegisterVariable(&net_slist_favorites);
3357 Cvar_RegisterVariable(&net_slist_pause);
3358 Cvar_RegisterVariable(&net_messagetimeout);
3359 Cvar_RegisterVariable(&net_connecttimeout);
3360 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3361 Cvar_RegisterVariable(&cl_netlocalping);
3362 Cvar_RegisterVariable(&cl_netpacketloss_send);
3363 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3364 Cvar_RegisterVariable(&hostname);
3365 Cvar_RegisterVariable(&developer_networking);
3366 Cvar_RegisterVariable(&cl_netport);
3367 Cvar_RegisterVariable(&sv_netport);
3368 Cvar_RegisterVariable(&net_address);
3369 Cvar_RegisterVariable(&net_address_ipv6);
3370 Cvar_RegisterVariable(&sv_public);
3371 Cvar_RegisterVariable(&sv_heartbeatperiod);
3372 for (i = 0;sv_masters[i].name;i++)
3373 Cvar_RegisterVariable(&sv_masters[i]);
3374 Cvar_RegisterVariable(&gameversion);
3375 Cvar_RegisterVariable(&gameversion_min);
3376 Cvar_RegisterVariable(&gameversion_max);
3377 // 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.
3378 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3380 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3382 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3383 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3386 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3388 // 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
3389 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3391 i = atoi(com_argv[i + 1]);
3392 if (i >= 0 && i < 65536)
3394 Con_Printf("-port option used, setting port cvar to %i\n", i);
3395 Cvar_SetValueQuick(&sv_netport, i);
3398 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3402 net_message.data = net_message_buf;
3403 net_message.maxsize = sizeof(net_message_buf);
3404 net_message.cursize = 0;
3408 void NetConn_Shutdown(void)
3410 NetConn_CloseClientPorts();
3411 NetConn_CloseServerPorts();