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 serverlist_entry_t *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] = entry;
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_viewlist[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_viewlist[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_viewlist[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_viewlist[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 i = (cls.rcon_ringpos + j) % MAX_RCONS;
1608 if(cls.rcon_commands[i][0])
1609 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1618 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1619 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1621 e = strchr(rcon_password.string, ' ');
1622 n = e ? e-rcon_password.string : (int)strlen(rcon_password.string);
1624 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, n))
1627 strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1628 NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1629 cls.rcon_commands[i][0] = 0;
1632 for (i = 0;i < MAX_RCONS;i++)
1633 if(cls.rcon_commands[i][0])
1634 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1638 NetConn_WriteString(mysocket, "\377\377\377\377getchallenge", peeraddress);
1639 // extend the timeout on other requests as we asked for a challenge
1640 for (i = 0;i < MAX_RCONS;i++)
1641 if(cls.rcon_commands[i][0])
1642 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1643 cls.rcon_timeout[i] = realtime + rcon_secure_challengetimeout.value;
1646 return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1650 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1652 // darkplaces or quake3
1653 char protocolnames[1400];
1654 Protocol_Names(protocolnames, sizeof(protocolnames));
1655 Con_DPrintf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1656 M_Update_Return_Reason("Got challenge response");
1657 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1658 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1659 // TODO: add userinfo stuff here instead of using NQ commands?
1660 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1663 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1665 // darkplaces or quake3
1666 M_Update_Return_Reason("Accepted");
1667 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1670 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1672 char rejectreason[32];
1673 cls.connect_trying = false;
1675 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1676 memcpy(rejectreason, string, length);
1677 rejectreason[length] = 0;
1678 M_Update_Return_Reason(rejectreason);
1681 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1683 serverlist_info_t *info;
1688 // search the cache for this server and update it
1689 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1693 info = &serverlist_cache[n].info;
1698 info->qcstatus[0] = 0;
1699 info->players[0] = 0;
1700 info->protocol = -1;
1701 info->numplayers = 0;
1703 info->maxplayers = 0;
1704 info->gameversion = 0;
1706 p = strchr(string, '\n');
1709 *p = 0; // cut off the string there
1713 Con_Printf("statusResponse without players block?\n");
1715 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1716 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1717 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1718 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1719 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1720 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1721 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1722 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1723 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1724 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1725 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1726 info->numhumans = info->numplayers - max(0, info->numbots);
1727 info->freeslots = info->maxplayers - info->numplayers;
1729 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1733 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1735 serverlist_info_t *info;
1739 // search the cache for this server and update it
1740 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1744 info = &serverlist_cache[n].info;
1749 info->qcstatus[0] = 0;
1750 info->players[0] = 0;
1751 info->protocol = -1;
1752 info->numplayers = 0;
1754 info->maxplayers = 0;
1755 info->gameversion = 0;
1757 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1758 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1759 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1760 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1761 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1762 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1763 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1764 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1765 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1766 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1767 info->numhumans = info->numplayers - max(0, info->numbots);
1768 info->freeslots = info->maxplayers - info->numplayers;
1770 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1774 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1776 // Extract the IP addresses
1779 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1782 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1784 // Extract the IP addresses
1787 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1790 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1792 // Extract the IP addresses
1796 if (serverlist_consoleoutput)
1797 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1798 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1800 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1801 if (serverlist_consoleoutput && developer_networking.integer)
1802 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1804 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1808 // move on to next address in packet
1812 // begin or resume serverlist queries
1813 serverlist_querysleep = false;
1814 serverlist_querywaittime = realtime + 3;
1817 if (!strncmp(string, "extResponse ", 12))
1819 ++cl_net_extresponse_count;
1820 if(cl_net_extresponse_count > NET_EXTRESPONSE_MAX)
1821 cl_net_extresponse_count = NET_EXTRESPONSE_MAX;
1822 cl_net_extresponse_last = (cl_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1823 dpsnprintf(cl_net_extresponse[cl_net_extresponse_last], sizeof(cl_net_extresponse[cl_net_extresponse_last]), "\"%s\" %s", addressstring2, string + 12);
1826 if (!strncmp(string, "ping", 4))
1828 if (developer_extra.integer)
1829 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
1830 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1833 if (!strncmp(string, "ack", 3))
1835 // QuakeWorld compatibility
1836 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1838 // challenge message
1839 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1840 M_Update_Return_Reason("Got QuakeWorld challenge response");
1841 cls.qw_qport = qport.integer;
1842 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1843 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1844 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1847 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1850 M_Update_Return_Reason("QuakeWorld Accepted");
1851 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1854 if (length > 2 && !memcmp(string, "n\\", 2))
1856 serverlist_info_t *info;
1860 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1861 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1864 // search the cache for this server and update it
1865 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1869 info = &serverlist_cache[n].info;
1870 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1871 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1872 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1873 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1875 info->numplayers = 0; // updated below
1876 info->numhumans = 0; // updated below
1877 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1878 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1880 // count active players on server
1881 // (we could gather more info, but we're just after the number)
1882 s = strchr(string, '\n');
1886 while (s < string + length)
1888 for (;s < string + length && *s != '\n';s++)
1890 if (s >= string + length)
1898 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1902 if (string[0] == 'n')
1905 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1907 // we may not have liked the packet, but it was a command packet, so
1908 // we're done processing this packet now
1911 // quakeworld ingame packet
1912 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1915 CL_ParseServerMessage();
1918 // netquake control packets, supported for compatibility only
1919 if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1922 serverlist_info_t *info;
1926 SZ_Clear(&net_message);
1927 SZ_Write(&net_message, data, length);
1933 if (developer_extra.integer)
1934 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1935 if (cls.connect_trying)
1937 lhnetaddress_t clientportaddress;
1938 clientportaddress = *peeraddress;
1939 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1940 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1941 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1942 M_Update_Return_Reason("Accepted");
1943 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1947 if (developer_extra.integer)
1948 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1949 cls.connect_trying = false;
1950 M_Update_Return_Reason((char *)MSG_ReadString());
1952 case CCREP_SERVER_INFO:
1953 if (developer_extra.integer)
1954 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1955 // LordHavoc: because the quake server may report weird addresses
1956 // we just ignore it and keep the real address
1958 // search the cache for this server and update it
1959 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1963 info = &serverlist_cache[n].info;
1964 strlcpy(info->game, "Quake", sizeof(info->game));
1965 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1966 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1967 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1968 info->numplayers = MSG_ReadByte();
1969 info->maxplayers = MSG_ReadByte();
1970 info->protocol = MSG_ReadByte();
1972 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1975 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1976 if (developer_extra.integer)
1977 Con_DPrintf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1979 Con_Printf("%s\n", MSG_ReadString());
1981 case CCREP_PLAYER_INFO:
1982 // we got a CCREP_PLAYER_INFO??
1983 //if (developer_extra.integer)
1984 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1986 case CCREP_RULE_INFO:
1987 // we got a CCREP_RULE_INFO??
1988 //if (developer_extra.integer)
1989 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1994 SZ_Clear(&net_message);
1995 // we may not have liked the packet, but it was a valid control
1996 // packet, so we're done processing this packet now
2000 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
2001 CL_ParseServerMessage();
2005 void NetConn_QueryQueueFrame(void)
2011 static double querycounter = 0;
2013 if(!net_slist_pause.integer && serverlist_paused)
2014 ServerList_RebuildViewList();
2015 serverlist_paused = net_slist_pause.integer != 0;
2017 if (serverlist_querysleep)
2020 // apply a cool down time after master server replies,
2021 // to avoid messing up the ping times on the servers
2022 if (serverlist_querywaittime > realtime)
2025 // each time querycounter reaches 1.0 issue a query
2026 querycounter += cl.realframetime * net_slist_queriespersecond.value;
2027 maxqueries = (int)querycounter;
2028 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
2029 querycounter -= maxqueries;
2031 if( maxqueries == 0 ) {
2035 // scan serverlist and issue queries as needed
2036 serverlist_querysleep = true;
2038 timeouttime = realtime - net_slist_timeout.value;
2039 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
2041 serverlist_entry_t *entry = &serverlist_cache[ index ];
2042 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
2047 serverlist_querysleep = false;
2048 if( entry->querycounter != 0 && entry->querytime > timeouttime )
2053 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
2055 lhnetaddress_t address;
2058 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
2059 if (entry->protocol == PROTOCOL_QUAKEWORLD)
2061 for (socket = 0; socket < cl_numsockets ; socket++)
2062 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
2066 for (socket = 0; socket < cl_numsockets ; socket++)
2067 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2070 // update the entry fields
2071 entry->querytime = realtime;
2072 entry->querycounter++;
2074 // if not in the slist menu we should print the server to console
2075 if (serverlist_consoleoutput)
2076 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2082 // have we tried to refresh this server?
2083 if( entry->query == SQS_REFRESHING ) {
2084 // yes, so update the reply count (since its not responding anymore)
2086 if(!serverlist_paused)
2087 ServerList_ViewList_Remove(entry);
2089 entry->query = SQS_TIMEDOUT;
2094 void NetConn_ClientFrame(void)
2097 lhnetaddress_t peeraddress;
2098 NetConn_UpdateSockets();
2099 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2101 if (cls.connect_remainingtries == 0)
2102 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2103 cls.connect_nextsendtime = realtime + 1;
2104 cls.connect_remainingtries--;
2105 if (cls.connect_remainingtries <= -10)
2107 cls.connect_trying = false;
2108 M_Update_Return_Reason("Connect: Failed");
2111 // try challenge first (newer DP server or QW)
2112 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2113 // then try netquake as a fallback (old server, or netquake)
2114 SZ_Clear(&net_message);
2115 // save space for the header, filled in later
2116 MSG_WriteLong(&net_message, 0);
2117 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2118 MSG_WriteString(&net_message, "QUAKE");
2119 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2120 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2121 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2122 SZ_Clear(&net_message);
2124 for (i = 0;i < cl_numsockets;i++)
2125 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2126 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2127 NetConn_QueryQueueFrame();
2128 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2130 Con_Print("Connection timed out\n");
2132 Host_ShutdownServer ();
2136 #define MAX_CHALLENGES 128
2139 lhnetaddress_t address;
2143 challenge[MAX_CHALLENGES];
2145 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2149 for (i = 0;i < bufferlength - 1;i++)
2153 c = rand () % (127 - 33) + 33;
2154 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2160 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2161 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2164 unsigned int nb_clients = 0, nb_bots = 0, i;
2170 // How many clients are there?
2171 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2173 if (svs.clients[i].active)
2176 if (!svs.clients[i].netconnection)
2182 if(prog->globaloffsets.worldstatus >= 0)
2184 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2190 for(q = str; *q; ++q)
2191 if(*q != '\\' && *q != '\n')
2197 /// \TODO: we should add more information for the full status string
2198 length = dpsnprintf(out_msg, out_size,
2199 "\377\377\377\377%s\x0A"
2200 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2201 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2205 fullstatus ? "statusResponse" : "infoResponse",
2206 gamename, com_modname, gameversion.integer, svs.maxclients,
2207 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2208 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2209 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2210 fullstatus ? "\n" : "");
2212 // Make sure it fits in the buffer
2222 savelength = length;
2224 ptr = out_msg + length;
2225 left = (int)out_size - length;
2227 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2229 client_t *cl = &svs.clients[i];
2232 int nameind, cleanind, pingvalue;
2234 char cleanname [sizeof(cl->name)];
2236 // Remove all characters '"' and '\' in the player name
2241 curchar = cl->name[nameind++];
2242 if (curchar != '"' && curchar != '\\')
2244 cleanname[cleanind++] = curchar;
2245 if (cleanind == sizeof(cleanname) - 1)
2248 } while (curchar != '\0');
2249 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2251 pingvalue = (int)(cl->ping * 1000.0f);
2252 if(cl->netconnection)
2253 pingvalue = bound(1, pingvalue, 9999);
2258 if(prog->fieldoffsets.clientstatus >= 0)
2260 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2266 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2267 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2273 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2275 if(cl->frags == -666) // spectator
2276 strlcpy(teambuf, " 0", sizeof(teambuf));
2277 else if(cl->colors == 0x44) // red team
2278 strlcpy(teambuf, " 1", sizeof(teambuf));
2279 else if(cl->colors == 0xDD) // blue team
2280 strlcpy(teambuf, " 2", sizeof(teambuf));
2281 else if(cl->colors == 0xCC) // yellow team
2282 strlcpy(teambuf, " 3", sizeof(teambuf));
2283 else if(cl->colors == 0x99) // pink team
2284 strlcpy(teambuf, " 4", sizeof(teambuf));
2286 strlcpy(teambuf, " 0", sizeof(teambuf));
2291 // note: team number is inserted according to SoF2 protocol
2293 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2299 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2308 // turn it into an infoResponse!
2309 out_msg[savelength] = 0;
2310 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2311 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2328 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2330 int floodslotnum, bestfloodslotnum;
2331 double bestfloodtime;
2332 lhnetaddress_t noportpeeraddress;
2333 // see if this is a connect flood
2334 noportpeeraddress = *peeraddress;
2335 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2336 bestfloodslotnum = 0;
2337 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2338 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2340 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2342 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2343 bestfloodslotnum = floodslotnum;
2345 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2347 // this address matches an ongoing flood address
2348 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2350 // renew the ban on this address so it does not expire
2351 // until the flood has subsided
2352 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2353 //Con_Printf("Flood detected!\n");
2356 // the flood appears to have subsided, so allow this
2357 bestfloodslotnum = floodslotnum; // reuse the same slot
2361 // begin a new timeout on this address
2362 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2363 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2364 //Con_Printf("Flood detection initiated!\n");
2368 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2371 lhnetaddress_t noportpeeraddress;
2372 // see if this is a connect flood
2373 noportpeeraddress = *peeraddress;
2374 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2375 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2377 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2379 // this address matches an ongoing flood address
2381 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2382 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2383 //Con_Printf("Flood cleared!\n");
2388 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2390 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2395 t1 = (long) time(NULL);
2396 t2 = strtol(s, NULL, 0);
2397 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2400 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2403 return !memcmp(mdfourbuf, hash, 16);
2406 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2411 if(slen < (int)(sizeof(challenge[0].string)) - 1)
2414 // validate the challenge
2415 for (i = 0;i < MAX_CHALLENGES;i++)
2416 if(challenge[i].time > 0)
2417 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2419 // if the challenge is not recognized, drop the packet
2420 if (i == MAX_CHALLENGES)
2423 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2426 if(memcmp(mdfourbuf, hash, 16))
2429 // unmark challenge to prevent replay attacks
2430 challenge[i].time = 0;
2435 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2437 return !strcmp(password, hash);
2440 /// returns a string describing the user level, or NULL for auth failure
2441 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)
2443 const char *text, *userpass_start, *userpass_end, *userpass_startpass;
2444 char buf[MAX_INPUTLINE];
2446 qboolean restricted = false;
2447 qboolean have_usernames = false;
2449 userpass_start = rcon_password.string;
2450 while((userpass_end = strchr(userpass_start, ' ')))
2452 have_usernames = true;
2453 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2455 if(comparator(peeraddress, buf, password, cs, cslen))
2457 userpass_start = userpass_end + 1;
2459 if(userpass_start[0])
2461 userpass_end = userpass_start + strlen(userpass_start);
2462 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2467 have_usernames = false;
2468 userpass_start = rcon_restricted_password.string;
2469 while((userpass_end = strchr(userpass_start, ' ')))
2471 have_usernames = true;
2472 strlcpy(buf, userpass_start, ((size_t)(userpass_end-userpass_start) >= sizeof(buf)) ? (int)(sizeof(buf)) : (int)(userpass_end-userpass_start+1));
2474 if(comparator(peeraddress, buf, password, cs, cslen))
2476 userpass_start = userpass_end + 1;
2478 if(userpass_start[0])
2480 userpass_end = userpass_start + strlen(userpass_start);
2481 if(comparator(peeraddress, userpass_start, password, cs, cslen))
2485 return NULL; // DENIED
2488 for(text = s; text != endpos; ++text)
2489 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2490 return NULL; // block possible exploits against the parser/alias expansion
2494 size_t l = strlen(s);
2497 hasquotes = (strchr(s, '"') != NULL);
2498 // sorry, we can't allow these substrings in wildcard expressions,
2499 // as they can mess with the argument counts
2500 text = rcon_restricted_commands.string;
2501 while(COM_ParseToken_Console(&text))
2503 // com_token now contains a pattern to check for...
2504 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2507 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2510 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2512 if(!strcmp(com_token, s))
2515 else // single-arg expression? must match the beginning of the command
2517 if(!strcmp(com_token, s))
2519 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2523 // if we got here, nothing matched!
2531 userpass_startpass = strchr(userpass_start, ':');
2532 if(have_usernames && userpass_startpass && userpass_startpass < userpass_end)
2533 return va("%srcon (username %.*s)", restricted ? "restricted " : "", (int)(userpass_startpass-userpass_start), userpass_start);
2535 return va("%srcon", restricted ? "restricted " : "");
2537 return "restricted rcon";
2540 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2544 // looks like a legitimate rcon command with the correct password
2545 const char *s_ptr = s;
2546 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2547 while(s_ptr != endpos)
2549 size_t l = strlen(s_ptr);
2551 Con_Printf(" %s;", s_ptr);
2556 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2557 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2560 size_t l = strlen(s);
2563 client_t *host_client_save = host_client;
2564 Cmd_ExecuteString(s, src_command);
2565 host_client = host_client_save;
2566 // in case it is a command that changes host_client (like restart)
2570 Con_Rcon_Redirect_End();
2574 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2578 extern void SV_SendServerinfo (client_t *client);
2579 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2581 int i, ret, clientnum, best;
2584 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2585 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2590 // convert the address to a string incase we need it
2591 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2593 // see if we can identify the sender as a local player
2594 // (this is necessary for rcon to send a reliable reply if the client is
2595 // actually on the server, not sending remotely)
2596 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2597 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2599 if (i == svs.maxclients)
2602 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2604 // received a command string - strip off the packaging and put it
2605 // into our string buffer with NULL termination
2608 length = min(length, (int)sizeof(stringbuf) - 1);
2609 memcpy(stringbuf, data, length);
2610 stringbuf[length] = 0;
2613 if (developer_extra.integer)
2615 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2616 Com_HexDumpToConsole(data, length);
2619 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2621 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2623 if(challenge[i].time > 0)
2624 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2626 if (besttime > challenge[i].time)
2627 besttime = challenge[best = i].time;
2629 // if we did not find an exact match, choose the oldest and
2630 // update address and string
2631 if (i == MAX_CHALLENGES)
2634 challenge[i].address = *peeraddress;
2635 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2637 challenge[i].time = realtime;
2638 // send the challenge
2639 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2642 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2647 if (!(s = SearchInfostring(string, "challenge")))
2649 // validate the challenge
2650 for (i = 0;i < MAX_CHALLENGES;i++)
2651 if(challenge[i].time > 0)
2652 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2654 // if the challenge is not recognized, drop the packet
2655 if (i == MAX_CHALLENGES)
2658 // check engine protocol
2659 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2661 if (developer_extra.integer)
2662 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2663 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2667 // see if this is a duplicate connection request or a disconnected
2668 // client who is rejoining to the same client slot
2669 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2671 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2673 // this is a known client...
2674 if (client->spawned)
2676 // client crashed and is coming back,
2677 // keep their stuff intact
2678 if (developer_extra.integer)
2679 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2680 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2682 SV_SendServerinfo(client);
2687 // client is still trying to connect,
2688 // so we send a duplicate reply
2689 if (developer_extra.integer)
2690 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2691 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2697 if (NetConn_PreventConnectFlood(peeraddress))
2700 // find an empty client slot for this new client
2701 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2704 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2706 // allocated connection
2707 if (developer_extra.integer)
2708 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2709 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2710 // now set up the client
2712 SV_ConnectClient(clientnum, conn);
2714 NetConn_Heartbeat(1);
2719 // no empty slots found - server is full
2720 if (developer_extra.integer)
2721 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2722 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2726 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2728 const char *challenge = NULL;
2730 // If there was a challenge in the getinfo message
2731 if (length > 8 && string[7] == ' ')
2732 challenge = string + 8;
2734 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2736 if (developer_extra.integer)
2737 Con_DPrintf("Sending reply to master %s - %s\n", addressstring2, response);
2738 NetConn_WriteString(mysocket, response, peeraddress);
2742 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2744 const char *challenge = NULL;
2746 // If there was a challenge in the getinfo message
2747 if (length > 10 && string[9] == ' ')
2748 challenge = string + 10;
2750 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2752 if (developer_extra.integer)
2753 Con_DPrintf("Sending reply to client %s - %s\n", addressstring2, response);
2754 NetConn_WriteString(mysocket, response, peeraddress);
2758 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2760 char *password = string + 20;
2761 char *timeval = string + 37;
2762 char *s = strchr(timeval, ' ');
2763 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2764 const char *userlevel;
2766 if(rcon_secure.integer > 1)
2770 return true; // invalid packet
2773 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2774 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2777 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
2779 char *password = string + 25;
2780 char *challenge = string + 42;
2781 char *s = strchr(challenge, ' ');
2782 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2783 const char *userlevel;
2785 return true; // invalid packet
2788 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
2789 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2792 if (length >= 5 && !memcmp(string, "rcon ", 5))
2795 char *s = string + 5;
2796 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2799 if(rcon_secure.integer > 0)
2802 for (i = 0;!ISWHITESPACE(*s);s++)
2803 if (i < (int)sizeof(password) - 1)
2805 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2808 if (!ISWHITESPACE(password[0]))
2810 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
2811 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2815 if (!strncmp(string, "extResponse ", 12))
2817 ++sv_net_extresponse_count;
2818 if(sv_net_extresponse_count > NET_EXTRESPONSE_MAX)
2819 sv_net_extresponse_count = NET_EXTRESPONSE_MAX;
2820 sv_net_extresponse_last = (sv_net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
2821 dpsnprintf(sv_net_extresponse[sv_net_extresponse_last], sizeof(sv_net_extresponse[sv_net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
2824 if (!strncmp(string, "ping", 4))
2826 if (developer_extra.integer)
2827 Con_DPrintf("Received ping from %s, sending ack\n", addressstring2);
2828 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2831 if (!strncmp(string, "ack", 3))
2833 // we may not have liked the packet, but it was a command packet, so
2834 // we're done processing this packet now
2837 // netquake control packets, supported for compatibility only, and only
2838 // when running game protocols that are normally served via this connection
2840 // (this protects more modern protocols against being used for
2841 // Quake packet flood Denial Of Service attacks)
2842 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))
2846 const char *protocolname;
2849 SZ_Clear(&net_message);
2850 SZ_Write(&net_message, data, length);
2856 if (developer_extra.integer)
2857 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2858 if(!islocal && sv_public.integer <= -2)
2861 protocolname = MSG_ReadString();
2862 protocolnumber = MSG_ReadByte();
2863 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2865 if (developer_extra.integer)
2866 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2867 SZ_Clear(&net_message);
2868 // save space for the header, filled in later
2869 MSG_WriteLong(&net_message, 0);
2870 MSG_WriteByte(&net_message, CCREP_REJECT);
2871 MSG_WriteString(&net_message, "Incompatible version.\n");
2872 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2873 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2874 SZ_Clear(&net_message);
2878 // see if this connect request comes from a known client
2879 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2881 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2883 // this is either a duplicate connection request
2884 // or coming back from a timeout
2885 // (if so, keep their stuff intact)
2888 if (developer_extra.integer)
2889 Con_DPrintf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2890 SZ_Clear(&net_message);
2891 // save space for the header, filled in later
2892 MSG_WriteLong(&net_message, 0);
2893 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2894 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2895 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2896 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2897 SZ_Clear(&net_message);
2899 // if client is already spawned, re-send the
2900 // serverinfo message as they'll need it to play
2901 if (client->spawned)
2904 SV_SendServerinfo(client);
2911 // this is a new client, check for connection flood
2912 if (NetConn_PreventConnectFlood(peeraddress))
2915 // find a slot for the new client
2916 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2919 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2921 // connect to the client
2922 // everything is allocated, just fill in the details
2923 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2924 if (developer_extra.integer)
2925 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2926 // send back the info about the server connection
2927 SZ_Clear(&net_message);
2928 // save space for the header, filled in later
2929 MSG_WriteLong(&net_message, 0);
2930 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2931 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2932 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2933 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2934 SZ_Clear(&net_message);
2935 // now set up the client struct
2937 SV_ConnectClient(clientnum, conn);
2939 NetConn_Heartbeat(1);
2944 if (developer_extra.integer)
2945 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2946 // no room; try to let player know
2947 SZ_Clear(&net_message);
2948 // save space for the header, filled in later
2949 MSG_WriteLong(&net_message, 0);
2950 MSG_WriteByte(&net_message, CCREP_REJECT);
2951 MSG_WriteString(&net_message, "Server is full.\n");
2952 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2953 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2954 SZ_Clear(&net_message);
2956 case CCREQ_SERVER_INFO:
2957 if (developer_extra.integer)
2958 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2959 if(!islocal && sv_public.integer <= -1)
2961 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2964 char myaddressstring[128];
2965 if (developer_extra.integer)
2966 Con_DPrintf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2967 SZ_Clear(&net_message);
2968 // save space for the header, filled in later
2969 MSG_WriteLong(&net_message, 0);
2970 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2971 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2972 MSG_WriteString(&net_message, myaddressstring);
2973 MSG_WriteString(&net_message, hostname.string);
2974 MSG_WriteString(&net_message, sv.name);
2975 // How many clients are there?
2976 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2977 if (svs.clients[i].active)
2979 MSG_WriteByte(&net_message, numclients);
2980 MSG_WriteByte(&net_message, svs.maxclients);
2981 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2982 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2983 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2984 SZ_Clear(&net_message);
2987 case CCREQ_PLAYER_INFO:
2988 if (developer_extra.integer)
2989 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2990 if(!islocal && sv_public.integer <= -1)
2994 int playerNumber, activeNumber, clientNumber;
2997 playerNumber = MSG_ReadByte();
2999 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
3000 if (client->active && ++activeNumber == playerNumber)
3002 if (clientNumber != svs.maxclients)
3004 SZ_Clear(&net_message);
3005 // save space for the header, filled in later
3006 MSG_WriteLong(&net_message, 0);
3007 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
3008 MSG_WriteByte(&net_message, playerNumber);
3009 MSG_WriteString(&net_message, client->name);
3010 MSG_WriteLong(&net_message, client->colors);
3011 MSG_WriteLong(&net_message, client->frags);
3012 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
3013 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
3014 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3015 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3016 SZ_Clear(&net_message);
3020 case CCREQ_RULE_INFO:
3021 if (developer_extra.integer)
3022 Con_DPrintf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
3023 if(!islocal && sv_public.integer <= -1)
3030 // find the search start location
3031 prevCvarName = MSG_ReadString();
3032 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
3034 // send the response
3035 SZ_Clear(&net_message);
3036 // save space for the header, filled in later
3037 MSG_WriteLong(&net_message, 0);
3038 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
3041 MSG_WriteString(&net_message, var->name);
3042 MSG_WriteString(&net_message, var->string);
3044 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3045 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
3046 SZ_Clear(&net_message);
3052 SZ_Clear(&net_message);
3053 // we may not have liked the packet, but it was a valid control
3054 // packet, so we're done processing this packet now
3059 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
3062 SV_ReadClientMessage();
3070 void NetConn_ServerFrame(void)
3073 lhnetaddress_t peeraddress;
3074 for (i = 0;i < sv_numsockets;i++)
3075 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
3076 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
3077 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
3079 // never timeout loopback connections
3080 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
3082 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
3084 SV_DropClient(false);
3090 void NetConn_SleepMicroseconds(int microseconds)
3092 LHNET_SleepUntilPacket_Microseconds(microseconds);
3095 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
3099 lhnetaddress_t masteraddress;
3100 lhnetaddress_t broadcastaddress;
3103 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
3106 // 26000 is the default quake server port, servers on other ports will not
3108 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
3109 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
3113 for (i = 0;i < cl_numsockets;i++)
3117 const char *cmdname, *extraoptions;
3118 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3120 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3122 // search LAN for Quake servers
3123 SZ_Clear(&net_message);
3124 // save space for the header, filled in later
3125 MSG_WriteLong(&net_message, 0);
3126 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
3127 MSG_WriteString(&net_message, "QUAKE");
3128 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3129 StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3130 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
3131 SZ_Clear(&net_message);
3133 // search LAN for DarkPlaces servers
3134 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3137 // build the getservers message to send to the dpmaster master servers
3138 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3140 cmdname = "getserversExt";
3141 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
3145 cmdname = "getservers";
3148 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3151 for (masternum = 0;sv_masters[masternum].name;masternum++)
3153 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3156 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3160 // search favorite servers
3161 for(j = 0; j < nFavorites; ++j)
3163 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3165 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3166 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3173 // only query QuakeWorld servers when the user wants to
3176 for (i = 0;i < cl_numsockets;i++)
3180 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3182 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3184 // search LAN for QuakeWorld servers
3185 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3187 // build the getservers message to send to the qwmaster master servers
3188 // note this has no -1 prefix, and the trailing nul byte is sent
3189 dpsnprintf(request, sizeof(request), "c\n");
3193 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3195 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3197 if (m_state != m_slist)
3199 char lookupstring[128];
3200 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3201 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3204 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3208 // search favorite servers
3209 for(j = 0; j < nFavorites; ++j)
3211 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3213 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3215 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3216 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3223 if (!masterquerycount)
3225 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3226 M_Update_Return_Reason("No network");
3230 void NetConn_Heartbeat(int priority)
3232 lhnetaddress_t masteraddress;
3234 lhnetsocket_t *mysocket;
3236 // if it's a state change (client connected), limit next heartbeat to no
3237 // more than 30 sec in the future
3238 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3239 nextheartbeattime = realtime + 30.0;
3241 // limit heartbeatperiod to 30 to 270 second range,
3242 // lower limit is to avoid abusing master servers with excess traffic,
3243 // upper limit is to avoid timing out on the master server (which uses
3245 if (sv_heartbeatperiod.value < 30)
3246 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3247 if (sv_heartbeatperiod.value > 270)
3248 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3250 // make advertising optional and don't advertise singleplayer games, and
3251 // only send a heartbeat as often as the admin wants
3252 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3254 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3255 for (masternum = 0;sv_masters[masternum].name;masternum++)
3256 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3257 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3261 static void Net_Heartbeat_f(void)
3264 NetConn_Heartbeat(2);
3266 Con_Print("No server running, can not heartbeat to master server.\n");
3269 void PrintStats(netconn_t *conn)
3271 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3272 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3274 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3277 void Net_Stats_f(void)
3280 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3281 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3282 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3283 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3284 Con_Printf("packetsSent = %i\n", packetsSent);
3285 Con_Printf("packetsReSent = %i\n", packetsReSent);
3286 Con_Printf("packetsReceived = %i\n", packetsReceived);
3287 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3288 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3289 Con_Print("connections =\n");
3290 for (conn = netconn_list;conn;conn = conn->next)
3294 void Net_Refresh_f(void)
3296 if (m_state != m_slist) {
3297 Con_Print("Sending new requests to master servers\n");
3298 ServerList_QueryList(false, true, false, true);
3299 Con_Print("Listening for replies...\n");
3301 ServerList_QueryList(false, true, false, false);
3304 void Net_Slist_f(void)
3306 ServerList_ResetMasks();
3307 serverlist_sortbyfield = SLIF_PING;
3308 serverlist_sortflags = 0;
3309 if (m_state != m_slist) {
3310 Con_Print("Sending requests to master servers\n");
3311 ServerList_QueryList(true, true, false, true);
3312 Con_Print("Listening for replies...\n");
3314 ServerList_QueryList(true, true, false, false);
3317 void Net_SlistQW_f(void)
3319 ServerList_ResetMasks();
3320 serverlist_sortbyfield = SLIF_PING;
3321 serverlist_sortflags = 0;
3322 if (m_state != m_slist) {
3323 Con_Print("Sending requests to master servers\n");
3324 ServerList_QueryList(true, false, true, true);
3325 serverlist_consoleoutput = true;
3326 Con_Print("Listening for replies...\n");
3328 ServerList_QueryList(true, false, true, false);
3331 void NetConn_Init(void)
3334 lhnetaddress_t tempaddress;
3335 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3336 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3337 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3338 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3339 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3340 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3341 Cvar_RegisterVariable(&rcon_restricted_password);
3342 Cvar_RegisterVariable(&rcon_restricted_commands);
3343 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3344 Cvar_RegisterVariable(&net_slist_queriespersecond);
3345 Cvar_RegisterVariable(&net_slist_queriesperframe);
3346 Cvar_RegisterVariable(&net_slist_timeout);
3347 Cvar_RegisterVariable(&net_slist_maxtries);
3348 Cvar_RegisterVariable(&net_slist_favorites);
3349 Cvar_RegisterVariable(&net_slist_pause);
3350 Cvar_RegisterVariable(&net_messagetimeout);
3351 Cvar_RegisterVariable(&net_connecttimeout);
3352 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3353 Cvar_RegisterVariable(&cl_netlocalping);
3354 Cvar_RegisterVariable(&cl_netpacketloss_send);
3355 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3356 Cvar_RegisterVariable(&hostname);
3357 Cvar_RegisterVariable(&developer_networking);
3358 Cvar_RegisterVariable(&cl_netport);
3359 Cvar_RegisterVariable(&sv_netport);
3360 Cvar_RegisterVariable(&net_address);
3361 Cvar_RegisterVariable(&net_address_ipv6);
3362 Cvar_RegisterVariable(&sv_public);
3363 Cvar_RegisterVariable(&sv_heartbeatperiod);
3364 for (i = 0;sv_masters[i].name;i++)
3365 Cvar_RegisterVariable(&sv_masters[i]);
3366 Cvar_RegisterVariable(&gameversion);
3367 Cvar_RegisterVariable(&gameversion_min);
3368 Cvar_RegisterVariable(&gameversion_max);
3369 // 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.
3370 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3372 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3374 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3375 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3378 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3380 // 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
3381 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3383 i = atoi(com_argv[i + 1]);
3384 if (i >= 0 && i < 65536)
3386 Con_Printf("-port option used, setting port cvar to %i\n", i);
3387 Cvar_SetValueQuick(&sv_netport, i);
3390 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3394 net_message.data = net_message_buf;
3395 net_message.maxsize = sizeof(net_message_buf);
3396 net_message.cursize = 0;
3400 void NetConn_Shutdown(void)
3402 NetConn_CloseClientPorts();
3403 NetConn_CloseServerPorts();