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"};
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;
92 /* statistic counters */
93 static int packetsSent = 0;
94 static int packetsReSent = 0;
95 static int packetsReceived = 0;
96 static int receivedDuplicateCount = 0;
97 static int droppedDatagrams = 0;
99 static int unreliableMessagesSent = 0;
100 static int unreliableMessagesReceived = 0;
101 static int reliableMessagesSent = 0;
102 static int reliableMessagesReceived = 0;
104 double masterquerytime = -1000;
105 int masterquerycount = 0;
106 int masterreplycount = 0;
107 int serverquerycount = 0;
108 int serverreplycount = 0;
110 /// this is only false if there are still servers left to query
111 static qboolean serverlist_querysleep = true;
112 static qboolean serverlist_paused = false;
113 /// this is pushed a second or two ahead of realtime whenever a master server
114 /// reply is received, to avoid issuing queries while master replies are still
115 /// flooding in (which would make a mess of the ping times)
116 static double serverlist_querywaittime = 0;
118 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
119 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
121 static int cl_numsockets;
122 static lhnetsocket_t *cl_sockets[16];
123 static int sv_numsockets;
124 static lhnetsocket_t *sv_sockets[16];
126 netconn_t *netconn_list = NULL;
127 mempool_t *netconn_mempool = NULL;
129 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
130 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
131 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
132 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
134 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
135 int net_extresponse_count = 0;
136 int net_extresponse_last = 0;
138 // ServerList interface
139 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
140 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
142 serverlist_infofield_t serverlist_sortbyfield;
143 int serverlist_sortflags;
145 int serverlist_viewcount = 0;
146 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
148 int serverlist_cachecount;
149 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
151 qboolean serverlist_consoleoutput;
153 static int nFavorites = 0;
154 static lhnetaddress_t favorites[256];
156 void NetConn_UpdateFavorites(void)
160 p = net_slist_favorites.string;
161 while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
163 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
168 /// helper function to insert a value into the viewset
169 /// spare entries will be removed
170 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
173 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
174 i = serverlist_viewcount++;
176 i = SERVERLIST_VIEWLISTSIZE - 1;
179 for( ; i > index ; i-- )
180 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
182 serverlist_viewlist[index] = entry;
185 /// we suppose serverlist_viewcount to be valid, ie > 0
186 static void _ServerList_ViewList_Helper_Remove( int index )
188 serverlist_viewcount--;
189 for( ; index < serverlist_viewcount ; index++ )
190 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
193 /// \returns true if A should be inserted before B
194 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
196 int result = 0; // > 0 if for numbers A > B and for text if A < B
198 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
200 if(A->info.isfavorite != B->info.isfavorite)
201 return A->info.isfavorite;
204 switch( serverlist_sortbyfield ) {
206 result = A->info.ping - B->info.ping;
208 case SLIF_MAXPLAYERS:
209 result = A->info.maxplayers - B->info.maxplayers;
211 case SLIF_NUMPLAYERS:
212 result = A->info.numplayers - B->info.numplayers;
215 result = A->info.numbots - B->info.numbots;
218 result = A->info.numhumans - B->info.numhumans;
221 result = A->info.freeslots - B->info.freeslots;
224 result = A->info.protocol - B->info.protocol;
227 result = strcmp( B->info.cname, A->info.cname );
230 result = strcasecmp( B->info.game, A->info.game );
233 result = strcasecmp( B->info.map, A->info.map );
236 result = strcasecmp( B->info.mod, A->info.mod );
239 result = strcasecmp( B->info.name, A->info.name );
242 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
244 case SLIF_ISFAVORITE:
245 result = !!B->info.isfavorite - !!A->info.isfavorite;
248 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
254 if( serverlist_sortflags & SLSF_DESCENDING )
260 // if the chosen sort key is identical, sort by index
261 // (makes this a stable sort, so that later replies from servers won't
262 // shuffle the servers around when they have the same ping)
266 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
268 // This should actually be done with some intermediate and end-of-function return
280 case SLMO_GREATEREQUAL:
282 case SLMO_NOTCONTAIN:
283 case SLMO_STARTSWITH:
284 case SLMO_NOTSTARTSWITH:
287 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
292 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
295 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
296 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
297 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
298 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
300 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
301 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
304 // Same here, also using an intermediate & final return would be more appropriate
308 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
309 case SLMO_NOTCONTAIN:
310 return !*bufferB || !strstr( bufferA, bufferB );
311 case SLMO_STARTSWITH:
312 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
313 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
314 case SLMO_NOTSTARTSWITH:
315 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
317 return strcmp( bufferA, bufferB ) < 0;
319 return strcmp( bufferA, bufferB ) <= 0;
321 return strcmp( bufferA, bufferB ) == 0;
323 return strcmp( bufferA, bufferB ) > 0;
325 return strcmp( bufferA, bufferB ) != 0;
326 case SLMO_GREATEREQUAL:
327 return strcmp( bufferA, bufferB ) >= 0;
329 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
334 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
336 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
338 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
340 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
342 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
344 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
346 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
348 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
350 if( *mask->info.cname
351 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
354 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
357 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
360 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
363 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
365 if( *mask->info.qcstatus
366 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
368 if( *mask->info.players
369 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
371 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
376 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
378 int start, end, mid, i;
381 // reject incompatible servers
383 entry->info.gameversion != gameversion.integer
386 gameversion_min.integer >= 0 // min/max range set by user/mod?
387 && gameversion_max.integer >= 0
388 && gameversion_min.integer >= entry->info.gameversion // version of server in min/max range?
389 && gameversion_max.integer <= entry->info.gameversion
394 // refresh the "favorite" status
395 entry->info.isfavorite = false;
396 if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
398 for(i = 0; i < nFavorites; ++i)
400 if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
402 entry->info.isfavorite = true;
408 // FIXME: change this to be more readable (...)
409 // now check whether it passes through the masks
410 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
411 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
414 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
415 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
417 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
420 if( !serverlist_viewcount ) {
421 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
424 // ok, insert it, we just need to find out where exactly:
427 // check whether to insert it as new first item
428 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
429 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
431 } // check whether to insert it as new last item
432 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
433 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
437 end = serverlist_viewcount - 1;
438 while( end > start + 1 )
440 mid = (start + end) / 2;
441 // test the item that lies in the middle between start and end
442 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
443 // the item has to be in the upper half
446 // the item has to be in the lower half
449 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
452 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
455 for( i = 0; i < serverlist_viewcount; i++ )
457 if (serverlist_viewlist[i] == entry)
459 _ServerList_ViewList_Helper_Remove(i);
465 void ServerList_RebuildViewList(void)
469 serverlist_viewcount = 0;
470 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
471 serverlist_entry_t *entry = &serverlist_cache[i];
472 // also display entries that are currently being refreshed [11/8/2007 Black]
473 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
474 ServerList_ViewList_Insert( entry );
478 void ServerList_ResetMasks(void)
482 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
483 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
484 // numbots needs to be compared to -1 to always succeed
485 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
486 serverlist_andmasks[i].info.numbots = -1;
487 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
488 serverlist_ormasks[i].info.numbots = -1;
491 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
494 int numplayers = 0, maxplayers = 0;
495 for (i = 0;i < serverlist_cachecount;i++)
497 if (serverlist_cache[i].query == SQS_QUERIED)
499 numplayers += serverlist_cache[i].info.numhumans;
500 maxplayers += serverlist_cache[i].info.maxplayers;
503 *numplayerspointer = numplayers;
504 *maxplayerspointer = maxplayers;
508 static void _ServerList_Test(void)
511 for( i = 0 ; i < 1024 ; i++ ) {
512 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
513 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
514 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
515 serverlist_cache[serverlist_cachecount].finished = true;
516 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 );
517 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
518 serverlist_cachecount++;
523 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
525 masterquerytime = realtime;
526 masterquerycount = 0;
527 masterreplycount = 0;
529 serverquerycount = 0;
530 serverreplycount = 0;
531 serverlist_cachecount = 0;
532 serverlist_viewcount = 0;
534 // refresh all entries
536 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
537 serverlist_entry_t *entry = &serverlist_cache[ n ];
538 entry->query = SQS_REFRESHING;
539 entry->querycounter = 0;
542 serverlist_consoleoutput = consoleoutput;
544 //_ServerList_Test();
546 NetConn_QueryMasters(querydp, queryqw);
551 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
553 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
557 if (cl_netpacketloss_receive.integer)
558 for (i = 0;i < cl_numsockets;i++)
559 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
561 if (developer_networking.integer)
563 char addressstring[128], addressstring2[128];
564 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
567 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
568 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
569 Com_HexDumpToConsole((unsigned char *)data, length);
572 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
577 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
581 if (cl_netpacketloss_send.integer)
582 for (i = 0;i < cl_numsockets;i++)
583 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
585 ret = LHNET_Write(mysocket, data, length, peeraddress);
586 if (developer_networking.integer)
588 char addressstring[128], addressstring2[128];
589 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
590 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
591 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)");
592 Com_HexDumpToConsole((unsigned char *)data, length);
597 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
599 // note this does not include the trailing NULL because we add that in the parser
600 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
603 qboolean NetConn_CanSend(netconn_t *conn)
605 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
606 conn->outgoing_netgraph[conn->outgoing_packetcounter].time = realtime;
607 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
608 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
609 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes = NETGRAPH_NOPACKET;
610 if (realtime > conn->cleartime)
614 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_CHOKEDPACKET;
619 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
623 // if this packet was supposedly choked, but we find ourselves sending one
624 // anyway, make sure the size counting starts at zero
625 // (this mostly happens on level changes and disconnects and such)
626 if (conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes == NETGRAPH_CHOKEDPACKET)
627 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
629 if (protocol == PROTOCOL_QUAKEWORLD)
632 qboolean sendreliable;
634 // note that it is ok to send empty messages to the qw server,
635 // otherwise it won't respond to us at all
637 sendreliable = false;
638 // if the remote side dropped the last reliable message, resend it
639 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
641 // if the reliable transmit buffer is empty, copy the current message out
642 if (!conn->sendMessageLength && conn->message.cursize)
644 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
645 conn->sendMessageLength = conn->message.cursize;
646 SZ_Clear(&conn->message); // clear the message buffer
647 conn->qw.reliable_sequence ^= 1;
650 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
651 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
652 // last received unreliable packet number, and last received reliable packet number (0 or 1)
653 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
655 conn->outgoing_unreliable_sequence++;
656 // client sends qport in every packet
657 if (conn == cls.netcon)
659 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
661 // also update cls.qw_outgoing_sequence
662 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
664 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
666 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
670 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
672 // add the reliable message if there is one
675 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += conn->sendMessageLength + 28;
676 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
677 packetLen += conn->sendMessageLength;
678 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
681 // add the unreliable message if possible
682 if (packetLen + data->cursize <= 1400)
684 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += data->cursize + 28;
685 memcpy(sendbuffer + packetLen, data->data, data->cursize);
686 packetLen += data->cursize;
689 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
692 unreliableMessagesSent++;
694 totallen += packetLen + 28;
698 unsigned int packetLen;
699 unsigned int dataLen;
701 unsigned int *header;
703 // if a reliable message fragment has been lost, send it again
704 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
706 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
708 dataLen = conn->sendMessageLength;
713 dataLen = MAX_PACKETFRAGMENT;
717 packetLen = NET_HEADERSIZE + dataLen;
719 header = (unsigned int *)sendbuffer;
720 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
721 header[1] = BigLong(conn->nq.sendSequence - 1);
722 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
724 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
726 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
728 conn->lastSendTime = realtime;
732 totallen += packetLen + 28;
735 // if we have a new reliable message to send, do so
736 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
738 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
740 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
741 conn->message.overflowed = true;
745 if (developer_networking.integer && conn == cls.netcon)
747 Con_Print("client sending reliable message to server:\n");
748 SZ_HexDumpToConsole(&conn->message);
751 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
752 conn->sendMessageLength = conn->message.cursize;
753 SZ_Clear(&conn->message);
755 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
757 dataLen = conn->sendMessageLength;
762 dataLen = MAX_PACKETFRAGMENT;
766 packetLen = NET_HEADERSIZE + dataLen;
768 header = (unsigned int *)sendbuffer;
769 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
770 header[1] = BigLong(conn->nq.sendSequence);
771 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
773 conn->nq.sendSequence++;
775 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
777 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
779 conn->lastSendTime = realtime;
781 reliableMessagesSent++;
783 totallen += packetLen + 28;
786 // if we have an unreliable message to send, do so
789 packetLen = NET_HEADERSIZE + data->cursize;
791 if (packetLen > (int)sizeof(sendbuffer))
793 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
797 header = (unsigned int *)sendbuffer;
798 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
799 header[1] = BigLong(conn->outgoing_unreliable_sequence);
800 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
802 conn->outgoing_unreliable_sequence++;
804 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
806 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
809 unreliableMessagesSent++;
811 totallen += packetLen + 28;
815 // delay later packets to obey rate limit
816 if (conn->cleartime < realtime - 0.1)
817 conn->cleartime = realtime - 0.1;
818 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
819 if (conn->cleartime < realtime)
820 conn->cleartime = realtime;
825 qboolean NetConn_HaveClientPorts(void)
827 return !!cl_numsockets;
830 qboolean NetConn_HaveServerPorts(void)
832 return !!sv_numsockets;
835 void NetConn_CloseClientPorts(void)
837 for (;cl_numsockets > 0;cl_numsockets--)
838 if (cl_sockets[cl_numsockets - 1])
839 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
842 void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
844 lhnetaddress_t address;
847 char addressstring2[1024];
848 if (addressstring && addressstring[0])
849 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
851 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
854 if ((s = LHNET_OpenSocket_Connectionless(&address)))
856 cl_sockets[cl_numsockets++] = s;
857 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
858 Con_Printf("Client opened a socket on address %s\n", addressstring2);
862 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
863 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
867 Con_Printf("Client unable to parse address %s\n", addressstring);
870 void NetConn_OpenClientPorts(void)
873 NetConn_CloseClientPorts();
874 port = bound(0, cl_netport.integer, 65535);
875 if (cl_netport.integer != port)
876 Cvar_SetValueQuick(&cl_netport, port);
878 Con_Printf("Client using an automatically assigned port\n");
880 Con_Printf("Client using port %i\n", port);
881 NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
882 NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
883 NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
886 void NetConn_CloseServerPorts(void)
888 for (;sv_numsockets > 0;sv_numsockets--)
889 if (sv_sockets[sv_numsockets - 1])
890 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
893 qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
895 lhnetaddress_t address;
898 char addressstring2[1024];
901 for (port = defaultport; port <= defaultport + range; port++)
903 if (addressstring && addressstring[0])
904 success = LHNETADDRESS_FromString(&address, addressstring, port);
906 success = LHNETADDRESS_FromPort(&address, addresstype, port);
909 if ((s = LHNET_OpenSocket_Connectionless(&address)))
911 sv_sockets[sv_numsockets++] = s;
912 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
913 Con_Printf("Server listening on address %s\n", addressstring2);
918 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
919 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
924 Con_Printf("Server unable to parse address %s\n", addressstring);
925 // if it cant parse one address, it wont be able to parse another for sure
932 void NetConn_OpenServerPorts(int opennetports)
935 NetConn_CloseServerPorts();
936 NetConn_UpdateSockets();
937 port = bound(0, sv_netport.integer, 65535);
940 Con_Printf("Server using port %i\n", port);
941 if (sv_netport.integer != port)
942 Cvar_SetValueQuick(&sv_netport, port);
943 if (cls.state != ca_dedicated)
944 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
947 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
948 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
950 if (sv_numsockets == 0)
951 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
954 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
956 int i, a = LHNETADDRESS_GetAddressType(address);
957 for (i = 0;i < cl_numsockets;i++)
958 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
959 return cl_sockets[i];
963 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
965 int i, a = LHNETADDRESS_GetAddressType(address);
966 for (i = 0;i < sv_numsockets;i++)
967 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
968 return sv_sockets[i];
972 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
975 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
976 conn->mysocket = mysocket;
977 conn->peeraddress = *peeraddress;
978 conn->lastMessageTime = realtime;
979 conn->message.data = conn->messagedata;
980 conn->message.maxsize = sizeof(conn->messagedata);
981 conn->message.cursize = 0;
982 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
983 // reduce effectiveness of connection request floods
984 conn->timeout = realtime + net_connecttimeout.value;
985 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
986 conn->next = netconn_list;
991 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
992 void NetConn_Close(netconn_t *conn)
995 // remove connection from list
997 // allow the client to reconnect immediately
998 NetConn_ClearConnectFlood(&(conn->peeraddress));
1000 if (conn == netconn_list)
1001 netconn_list = conn->next;
1004 for (c = netconn_list;c;c = c->next)
1006 if (c->next == conn)
1008 c->next = conn->next;
1012 // not found in list, we'll avoid crashing here...
1020 static int clientport = -1;
1021 static int clientport2 = -1;
1022 static int hostport = -1;
1023 void NetConn_UpdateSockets(void)
1025 if (cls.state != ca_dedicated)
1027 if (clientport2 != cl_netport.integer)
1029 clientport2 = cl_netport.integer;
1030 if (cls.state == ca_connected)
1031 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1033 if (cls.state == ca_disconnected && clientport != clientport2)
1035 clientport = clientport2;
1036 NetConn_CloseClientPorts();
1038 if (cl_numsockets == 0)
1039 NetConn_OpenClientPorts();
1042 if (hostport != sv_netport.integer)
1044 hostport = sv_netport.integer;
1046 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1050 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1052 int originallength = length;
1056 if (protocol == PROTOCOL_QUAKEWORLD)
1058 int sequence, sequence_ack;
1059 int reliable_ack, reliable_message;
1063 sequence = LittleLong(*((int *)(data + 0)));
1064 sequence_ack = LittleLong(*((int *)(data + 4)));
1068 if (conn != cls.netcon)
1073 // 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?)
1074 qport = LittleShort(*((int *)(data + 8)));
1080 reliable_message = (sequence >> 31) & 1;
1081 reliable_ack = (sequence_ack >> 31) & 1;
1082 sequence &= ~(1<<31);
1083 sequence_ack &= ~(1<<31);
1084 if (sequence <= conn->qw.incoming_sequence)
1086 //Con_DPrint("Got a stale datagram\n");
1089 count = sequence - (conn->qw.incoming_sequence + 1);
1092 droppedDatagrams += count;
1093 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1096 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1097 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1098 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1099 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1100 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1103 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1104 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1105 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1106 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1107 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1108 if (reliable_ack == conn->qw.reliable_sequence)
1110 // received, now we will be able to send another reliable message
1111 conn->sendMessageLength = 0;
1112 reliableMessagesReceived++;
1114 conn->qw.incoming_sequence = sequence;
1115 if (conn == cls.netcon)
1116 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1117 conn->qw.incoming_acknowledged = sequence_ack;
1118 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1119 if (reliable_message)
1120 conn->qw.incoming_reliable_sequence ^= 1;
1121 conn->lastMessageTime = realtime;
1122 conn->timeout = realtime + newtimeout;
1123 unreliableMessagesReceived++;
1124 SZ_Clear(&net_message);
1125 SZ_Write(&net_message, data, length);
1133 unsigned int sequence;
1136 qlength = (unsigned int)BigLong(((int *)data)[0]);
1137 flags = qlength & ~NETFLAG_LENGTH_MASK;
1138 qlength &= NETFLAG_LENGTH_MASK;
1139 // control packets were already handled
1140 if (!(flags & NETFLAG_CTL) && qlength == length)
1142 sequence = BigLong(((int *)data)[1]);
1146 if (flags & NETFLAG_UNRELIABLE)
1148 if (sequence >= conn->nq.unreliableReceiveSequence)
1150 if (sequence > conn->nq.unreliableReceiveSequence)
1152 count = sequence - conn->nq.unreliableReceiveSequence;
1153 droppedDatagrams += count;
1154 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1157 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1158 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1159 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1160 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1161 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1164 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1165 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1166 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1167 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1168 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1169 conn->nq.unreliableReceiveSequence = sequence + 1;
1170 conn->lastMessageTime = realtime;
1171 conn->timeout = realtime + newtimeout;
1172 unreliableMessagesReceived++;
1175 SZ_Clear(&net_message);
1176 SZ_Write(&net_message, data, length);
1182 // Con_DPrint("Got a stale datagram\n");
1185 else if (flags & NETFLAG_ACK)
1187 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1188 if (sequence == (conn->nq.sendSequence - 1))
1190 if (sequence == conn->nq.ackSequence)
1192 conn->nq.ackSequence++;
1193 if (conn->nq.ackSequence != conn->nq.sendSequence)
1194 Con_DPrint("ack sequencing error\n");
1195 conn->lastMessageTime = realtime;
1196 conn->timeout = realtime + newtimeout;
1197 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1199 unsigned int packetLen;
1200 unsigned int dataLen;
1202 unsigned int *header;
1204 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1205 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1207 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1209 dataLen = conn->sendMessageLength;
1214 dataLen = MAX_PACKETFRAGMENT;
1218 packetLen = NET_HEADERSIZE + dataLen;
1220 header = (unsigned int *)sendbuffer;
1221 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1222 header[1] = BigLong(conn->nq.sendSequence);
1223 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1225 conn->nq.sendSequence++;
1227 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1229 conn->lastSendTime = realtime;
1234 conn->sendMessageLength = 0;
1237 // Con_DPrint("Duplicate ACK received\n");
1240 // Con_DPrint("Stale ACK received\n");
1243 else if (flags & NETFLAG_DATA)
1245 unsigned int temppacket[2];
1246 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes += originallength + 28;
1247 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes += 8 + 28;
1248 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1249 temppacket[1] = BigLong(sequence);
1250 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1251 if (sequence == conn->nq.receiveSequence)
1253 conn->lastMessageTime = realtime;
1254 conn->timeout = realtime + newtimeout;
1255 conn->nq.receiveSequence++;
1256 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1257 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1258 conn->receiveMessageLength += length;
1260 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1261 "Dropping the message!\n", sequence );
1262 conn->receiveMessageLength = 0;
1265 if (flags & NETFLAG_EOM)
1267 reliableMessagesReceived++;
1268 length = conn->receiveMessageLength;
1269 conn->receiveMessageLength = 0;
1272 SZ_Clear(&net_message);
1273 SZ_Write(&net_message, conn->receiveMessage, length);
1280 receivedDuplicateCount++;
1288 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1290 cls.connect_trying = false;
1291 M_Update_Return_Reason("");
1292 // the connection request succeeded, stop current connection and set up a new connection
1294 // if we're connecting to a remote server, shut down any local server
1295 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1296 Host_ShutdownServer ();
1297 // allocate a net connection to keep track of things
1298 cls.netcon = NetConn_Open(mysocket, peeraddress);
1299 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1300 key_dest = key_game;
1302 cls.demonum = -1; // not in the demo loop now
1303 cls.state = ca_connected;
1304 cls.signon = 0; // need all the signon messages before playing
1305 cls.protocol = initialprotocol;
1306 // reset move sequence numbering on this new connection
1307 cls.servermovesequence = 0;
1308 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1309 Cmd_ForwardStringToServer("new");
1310 if (cls.protocol == PROTOCOL_QUAKE)
1312 // write a keepalive (clc_nop) as it seems to greatly improve the
1313 // chances of connecting to a netquake server
1315 unsigned char buf[4];
1316 memset(&msg, 0, sizeof(msg));
1318 msg.maxsize = sizeof(buf);
1319 MSG_WriteChar(&msg, clc_nop);
1320 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1324 int NetConn_IsLocalGame(void)
1326 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1331 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1335 serverlist_entry_t *entry = NULL;
1337 // search the cache for this server and update it
1338 for (n = 0;n < serverlist_cachecount;n++) {
1339 entry = &serverlist_cache[ n ];
1340 if (!strcmp(addressstring, entry->info.cname))
1344 if (n == serverlist_cachecount)
1346 // LAN search doesnt require an answer from the master server so we wont
1347 // know the ping nor will it be initialized already...
1350 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1353 entry = &serverlist_cache[n];
1355 memset(entry, 0, sizeof(*entry));
1356 // store the data the engine cares about (address and ping)
1357 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1358 entry->info.ping = 100000;
1359 entry->querytime = realtime;
1360 // if not in the slist menu we should print the server to console
1361 if (serverlist_consoleoutput)
1362 Con_Printf("querying %s\n", addressstring);
1363 ++serverlist_cachecount;
1365 // if this is the first reply from this server, count it as having replied
1366 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1367 pingtime = bound(0, pingtime, 9999);
1368 if (entry->query == SQS_REFRESHING) {
1369 entry->info.ping = pingtime;
1370 entry->query = SQS_QUERIED;
1372 // convert to unsigned to catch the -1
1373 // 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]
1374 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1378 // other server info is updated by the caller
1382 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1384 serverlist_entry_t *entry = &serverlist_cache[n];
1385 serverlist_info_t *info = &entry->info;
1386 // update description strings for engine menu and console output
1387 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);
1388 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1390 info->gameversion != gameversion.integer
1393 gameversion_min.integer >= 0 // min/max range set by user/mod?
1394 && gameversion_max.integer >= 0
1395 && gameversion_min.integer >= info->gameversion // version of server in min/max range?
1396 && gameversion_max.integer <= info->gameversion
1399 info->mod, info->map);
1400 if (entry->query == SQS_QUERIED)
1402 if(!serverlist_paused)
1403 ServerList_ViewList_Remove(entry);
1405 // if not in the slist menu we should print the server to console (if wanted)
1406 else if( serverlist_consoleoutput )
1407 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1408 // and finally, update the view set
1409 if(!serverlist_paused)
1410 ServerList_ViewList_Insert( entry );
1411 // update the entry's state
1412 serverlist_cache[n].query = SQS_QUERIED;
1415 // returns true, if it's sensible to continue the processing
1416 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1418 serverlist_entry_t *entry;
1420 // ignore the rest of the message if the serverlist is full
1421 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1423 // also ignore it if we have already queried it (other master server response)
1424 for( n = 0 ; n < serverlist_cachecount ; n++ )
1425 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1428 entry = &serverlist_cache[n];
1430 if( n < serverlist_cachecount ) {
1431 // the entry has already been queried once or
1435 memset(entry, 0, sizeof(entry));
1436 entry->protocol = protocol;
1437 // store the data the engine cares about (address and ping)
1438 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1440 entry->info.isfavorite = isfavorite;
1442 // no, then reset the ping right away
1443 entry->info.ping = -1;
1444 // we also want to increase the serverlist_cachecount then
1445 serverlist_cachecount++;
1448 entry->query = SQS_QUERYING;
1453 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1456 if (serverlist_consoleoutput)
1457 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1460 char ipstring [128];
1463 if (data[0] == '\\')
1465 unsigned short port = data[5] * 256 + data[6];
1467 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1468 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1470 // move on to next address in packet
1475 else if (data[0] == '/' && isextended && length >= 19)
1477 unsigned short port = data[17] * 256 + data[18];
1483 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1485 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1488 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1489 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1490 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1495 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1496 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1497 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1502 // move on to next address in packet
1508 Con_Print("Error while parsing the server list\n");
1512 if (serverlist_consoleoutput && developer_networking.integer)
1513 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1515 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1521 // begin or resume serverlist queries
1522 serverlist_querysleep = false;
1523 serverlist_querywaittime = realtime + 3;
1526 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1528 qboolean fromserver;
1529 int ret, c, control;
1531 char *string, addressstring2[128], ipstring[32];
1532 char stringbuf[16384];
1534 // quakeworld ingame packet
1535 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1537 // convert the address to a string incase we need it
1538 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1540 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1542 // received a command string - strip off the packaging and put it
1543 // into our string buffer with NULL termination
1546 length = min(length, (int)sizeof(stringbuf) - 1);
1547 memcpy(stringbuf, data, length);
1548 stringbuf[length] = 0;
1551 if (developer_networking.integer)
1553 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1554 Com_HexDumpToConsole(data, length);
1557 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1559 // darkplaces or quake3
1560 char protocolnames[1400];
1561 Protocol_Names(protocolnames, sizeof(protocolnames));
1562 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1563 M_Update_Return_Reason("Got challenge response");
1564 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1565 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1566 // TODO: add userinfo stuff here instead of using NQ commands?
1567 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1570 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1572 // darkplaces or quake3
1573 M_Update_Return_Reason("Accepted");
1574 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1577 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1579 char rejectreason[32];
1580 cls.connect_trying = false;
1582 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1583 memcpy(rejectreason, string, length);
1584 rejectreason[length] = 0;
1585 M_Update_Return_Reason(rejectreason);
1588 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1590 serverlist_info_t *info;
1595 // search the cache for this server and update it
1596 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1600 info = &serverlist_cache[n].info;
1605 info->qcstatus[0] = 0;
1606 info->players[0] = 0;
1607 info->protocol = -1;
1608 info->numplayers = 0;
1610 info->maxplayers = 0;
1611 info->gameversion = 0;
1613 p = strchr(string, '\n');
1616 *p = 0; // cut off the string there
1620 Con_Printf("statusResponse without players block?\n");
1622 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1623 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1624 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1625 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1626 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1627 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1628 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1629 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1630 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1631 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1632 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1633 info->numhumans = info->numplayers - max(0, info->numbots);
1634 info->freeslots = info->maxplayers - info->numplayers;
1636 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1640 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1642 serverlist_info_t *info;
1646 // search the cache for this server and update it
1647 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1651 info = &serverlist_cache[n].info;
1656 info->qcstatus[0] = 0;
1657 info->players[0] = 0;
1658 info->protocol = -1;
1659 info->numplayers = 0;
1661 info->maxplayers = 0;
1662 info->gameversion = 0;
1664 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1665 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1666 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1667 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1668 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1669 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1670 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1671 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1672 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1673 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1674 info->numhumans = info->numplayers - max(0, info->numbots);
1675 info->freeslots = info->maxplayers - info->numplayers;
1677 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1681 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1683 // Extract the IP addresses
1686 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1689 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1691 // Extract the IP addresses
1694 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1697 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1699 // Extract the IP addresses
1703 if (serverlist_consoleoutput)
1704 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1705 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1707 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1708 if (serverlist_consoleoutput && developer_networking.integer)
1709 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1711 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1715 // move on to next address in packet
1719 // begin or resume serverlist queries
1720 serverlist_querysleep = false;
1721 serverlist_querywaittime = realtime + 3;
1724 if (!strncmp(string, "extResponse ", 12))
1726 ++net_extresponse_count;
1727 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1728 net_extresponse_count = NET_EXTRESPONSE_MAX;
1729 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1730 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1733 if (!strncmp(string, "ping", 4))
1735 if (developer.integer >= 10)
1736 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1737 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1740 if (!strncmp(string, "ack", 3))
1742 // QuakeWorld compatibility
1743 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1745 // challenge message
1746 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1747 M_Update_Return_Reason("Got QuakeWorld challenge response");
1748 cls.qw_qport = qport.integer;
1749 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1750 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1751 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1754 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1757 M_Update_Return_Reason("QuakeWorld Accepted");
1758 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1761 if (length > 2 && !memcmp(string, "n\\", 2))
1763 serverlist_info_t *info;
1767 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1768 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1771 // search the cache for this server and update it
1772 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1776 info = &serverlist_cache[n].info;
1777 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1778 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1779 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1780 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1782 info->numplayers = 0; // updated below
1783 info->numhumans = 0; // updated below
1784 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1785 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1787 // count active players on server
1788 // (we could gather more info, but we're just after the number)
1789 s = strchr(string, '\n');
1793 while (s < string + length)
1795 for (;s < string + length && *s != '\n';s++)
1797 if (s >= string + length)
1805 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1809 if (string[0] == 'n')
1812 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1814 // we may not have liked the packet, but it was a command packet, so
1815 // we're done processing this packet now
1818 // quakeworld ingame packet
1819 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1822 CL_ParseServerMessage();
1825 // netquake control packets, supported for compatibility only
1826 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1829 serverlist_info_t *info;
1833 SZ_Clear(&net_message);
1834 SZ_Write(&net_message, data, length);
1840 if (developer.integer >= 10)
1841 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1842 if (cls.connect_trying)
1844 lhnetaddress_t clientportaddress;
1845 clientportaddress = *peeraddress;
1846 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1847 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1848 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1849 M_Update_Return_Reason("Accepted");
1850 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1854 if (developer.integer >= 10)
1855 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1856 cls.connect_trying = false;
1857 M_Update_Return_Reason((char *)MSG_ReadString());
1859 case CCREP_SERVER_INFO:
1860 if (developer.integer >= 10)
1861 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1862 // LordHavoc: because the quake server may report weird addresses
1863 // we just ignore it and keep the real address
1865 // search the cache for this server and update it
1866 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1870 info = &serverlist_cache[n].info;
1871 strlcpy(info->game, "Quake", sizeof(info->game));
1872 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1873 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1874 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1875 info->numplayers = MSG_ReadByte();
1876 info->maxplayers = MSG_ReadByte();
1877 info->protocol = MSG_ReadByte();
1879 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1882 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1883 if (developer.integer >= 10)
1884 Con_Printf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1886 Con_Printf("%s\n", MSG_ReadString());
1888 case CCREP_PLAYER_INFO:
1889 // we got a CCREP_PLAYER_INFO??
1890 //if (developer.integer >= 10)
1891 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1893 case CCREP_RULE_INFO:
1894 // we got a CCREP_RULE_INFO??
1895 //if (developer.integer >= 10)
1896 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1901 SZ_Clear(&net_message);
1902 // we may not have liked the packet, but it was a valid control
1903 // packet, so we're done processing this packet now
1907 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1908 CL_ParseServerMessage();
1912 void NetConn_QueryQueueFrame(void)
1918 static double querycounter = 0;
1920 if(!net_slist_pause.integer && serverlist_paused)
1921 ServerList_RebuildViewList();
1922 serverlist_paused = net_slist_pause.integer != 0;
1924 if (serverlist_querysleep)
1927 // apply a cool down time after master server replies,
1928 // to avoid messing up the ping times on the servers
1929 if (serverlist_querywaittime > realtime)
1932 // each time querycounter reaches 1.0 issue a query
1933 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1934 maxqueries = (int)querycounter;
1935 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1936 querycounter -= maxqueries;
1938 if( maxqueries == 0 ) {
1942 // scan serverlist and issue queries as needed
1943 serverlist_querysleep = true;
1945 timeouttime = realtime - net_slist_timeout.value;
1946 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1948 serverlist_entry_t *entry = &serverlist_cache[ index ];
1949 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1954 serverlist_querysleep = false;
1955 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1960 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1962 lhnetaddress_t address;
1965 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1966 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1968 for (socket = 0; socket < cl_numsockets ; socket++)
1969 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1973 for (socket = 0; socket < cl_numsockets ; socket++)
1974 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1977 // update the entry fields
1978 entry->querytime = realtime;
1979 entry->querycounter++;
1981 // if not in the slist menu we should print the server to console
1982 if (serverlist_consoleoutput)
1983 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1989 // have we tried to refresh this server?
1990 if( entry->query == SQS_REFRESHING ) {
1991 // yes, so update the reply count (since its not responding anymore)
1993 if(!serverlist_paused)
1994 ServerList_ViewList_Remove(entry);
1996 entry->query = SQS_TIMEDOUT;
2001 void NetConn_ClientFrame(void)
2004 lhnetaddress_t peeraddress;
2005 NetConn_UpdateSockets();
2006 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2008 if (cls.connect_remainingtries == 0)
2009 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2010 cls.connect_nextsendtime = realtime + 1;
2011 cls.connect_remainingtries--;
2012 if (cls.connect_remainingtries <= -10)
2014 cls.connect_trying = false;
2015 M_Update_Return_Reason("Connect: Failed");
2018 // try challenge first (newer DP server or QW)
2019 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2020 // then try netquake as a fallback (old server, or netquake)
2021 SZ_Clear(&net_message);
2022 // save space for the header, filled in later
2023 MSG_WriteLong(&net_message, 0);
2024 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2025 MSG_WriteString(&net_message, "QUAKE");
2026 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2027 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2028 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2029 SZ_Clear(&net_message);
2031 for (i = 0;i < cl_numsockets;i++)
2032 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2033 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2034 NetConn_QueryQueueFrame();
2035 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2037 Con_Print("Connection timed out\n");
2039 Host_ShutdownServer ();
2043 #define MAX_CHALLENGES 128
2046 lhnetaddress_t address;
2050 challenge[MAX_CHALLENGES];
2052 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2056 for (i = 0;i < bufferlength - 1;i++)
2060 c = rand () % (127 - 33) + 33;
2061 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2067 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2068 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2071 unsigned int nb_clients = 0, nb_bots = 0, i;
2077 // How many clients are there?
2078 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2080 if (svs.clients[i].active)
2083 if (!svs.clients[i].netconnection)
2089 if(prog->globaloffsets.worldstatus >= 0)
2091 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2097 for(q = str; *q; ++q)
2098 if(*q != '\\' && *q != '\n')
2104 /// \TODO: we should add more information for the full status string
2105 length = dpsnprintf(out_msg, out_size,
2106 "\377\377\377\377%s\x0A"
2107 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2108 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2112 fullstatus ? "statusResponse" : "infoResponse",
2113 gamename, com_modname, gameversion.integer, svs.maxclients,
2114 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2115 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2116 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2117 fullstatus ? "\n" : "");
2119 // Make sure it fits in the buffer
2129 savelength = length;
2131 ptr = out_msg + length;
2132 left = (int)out_size - length;
2134 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2136 client_t *cl = &svs.clients[i];
2139 int nameind, cleanind, pingvalue;
2141 char cleanname [sizeof(cl->name)];
2143 // Remove all characters '"' and '\' in the player name
2148 curchar = cl->name[nameind++];
2149 if (curchar != '"' && curchar != '\\')
2151 cleanname[cleanind++] = curchar;
2152 if (cleanind == sizeof(cleanname) - 1)
2155 } while (curchar != '\0');
2156 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2158 pingvalue = (int)(cl->ping * 1000.0f);
2159 if(cl->netconnection)
2160 pingvalue = bound(1, pingvalue, 9999);
2165 if(prog->fieldoffsets.clientstatus >= 0)
2167 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2173 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2174 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2180 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2182 if(cl->frags == -666) // spectator
2183 strlcpy(teambuf, " 0", sizeof(teambuf));
2184 else if(cl->colors == 0x44) // red team
2185 strlcpy(teambuf, " 1", sizeof(teambuf));
2186 else if(cl->colors == 0xDD) // blue team
2187 strlcpy(teambuf, " 2", sizeof(teambuf));
2188 else if(cl->colors == 0xCC) // yellow team
2189 strlcpy(teambuf, " 3", sizeof(teambuf));
2190 else if(cl->colors == 0x99) // pink team
2191 strlcpy(teambuf, " 4", sizeof(teambuf));
2193 strlcpy(teambuf, " 0", sizeof(teambuf));
2198 // note: team number is inserted according to SoF2 protocol
2200 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2206 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2215 // turn it into an infoResponse!
2216 out_msg[savelength] = 0;
2217 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2218 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2235 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2237 int floodslotnum, bestfloodslotnum;
2238 double bestfloodtime;
2239 lhnetaddress_t noportpeeraddress;
2240 // see if this is a connect flood
2241 noportpeeraddress = *peeraddress;
2242 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2243 bestfloodslotnum = 0;
2244 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2245 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2247 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2249 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2250 bestfloodslotnum = floodslotnum;
2252 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2254 // this address matches an ongoing flood address
2255 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2257 // renew the ban on this address so it does not expire
2258 // until the flood has subsided
2259 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2260 //Con_Printf("Flood detected!\n");
2263 // the flood appears to have subsided, so allow this
2264 bestfloodslotnum = floodslotnum; // reuse the same slot
2268 // begin a new timeout on this address
2269 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2270 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2271 //Con_Printf("Flood detection initiated!\n");
2275 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2278 lhnetaddress_t noportpeeraddress;
2279 // see if this is a connect flood
2280 noportpeeraddress = *peeraddress;
2281 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2282 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2284 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2286 // this address matches an ongoing flood address
2288 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2289 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2290 //Con_Printf("Flood cleared!\n");
2295 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2297 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2302 t1 = (long) time(NULL);
2303 t2 = strtol(s, NULL, 0);
2304 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2307 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2310 return !memcmp(mdfourbuf, hash, 16);
2313 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2315 return !strcmp(password, hash);
2318 /// returns a string describing the user level, or NULL for auth failure
2319 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2324 if(comparator(rcon_password.string, password, cs, cslen))
2327 if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2330 for(text = s; text != endpos; ++text)
2331 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2332 return NULL; // block possible exploits against the parser/alias expansion
2336 size_t l = strlen(s);
2339 hasquotes = (strchr(s, '"') != NULL);
2340 // sorry, we can't allow these substrings in wildcard expressions,
2341 // as they can mess with the argument counts
2342 text = rcon_restricted_commands.string;
2343 while(COM_ParseToken_Console(&text))
2345 // com_token now contains a pattern to check for...
2346 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2349 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2352 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2354 if(!strcmp(com_token, s))
2357 else // single-arg expression? must match the beginning of the command
2359 if(!strcmp(com_token, s))
2361 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2365 // if we got here, nothing matched!
2372 return "restricted rcon";
2375 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2379 // looks like a legitimate rcon command with the correct password
2380 const char *s_ptr = s;
2381 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2382 while(s_ptr != endpos)
2384 size_t l = strlen(s_ptr);
2386 Con_Printf(" %s;", s_ptr);
2391 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2392 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2395 size_t l = strlen(s);
2398 client_t *host_client_save = host_client;
2399 Cmd_ExecuteString(s, src_command);
2400 host_client = host_client_save;
2401 // in case it is a command that changes host_client (like restart)
2405 Con_Rcon_Redirect_End();
2409 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2413 extern void SV_SendServerinfo (client_t *client);
2414 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2416 int i, ret, clientnum, best;
2419 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2420 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2425 // convert the address to a string incase we need it
2426 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2428 // see if we can identify the sender as a local player
2429 // (this is necessary for rcon to send a reliable reply if the client is
2430 // actually on the server, not sending remotely)
2431 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2432 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2434 if (i == svs.maxclients)
2437 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2439 // received a command string - strip off the packaging and put it
2440 // into our string buffer with NULL termination
2443 length = min(length, (int)sizeof(stringbuf) - 1);
2444 memcpy(stringbuf, data, length);
2445 stringbuf[length] = 0;
2448 if (developer.integer >= 10)
2450 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2451 Com_HexDumpToConsole(data, length);
2454 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2456 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2458 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2460 if (besttime > challenge[i].time)
2461 besttime = challenge[best = i].time;
2463 // if we did not find an exact match, choose the oldest and
2464 // update address and string
2465 if (i == MAX_CHALLENGES)
2468 challenge[i].address = *peeraddress;
2469 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2471 challenge[i].time = realtime;
2472 // send the challenge
2473 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2476 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2481 if (!(s = SearchInfostring(string, "challenge")))
2483 // validate the challenge
2484 for (i = 0;i < MAX_CHALLENGES;i++)
2485 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2487 // if the challenge is not recognized, drop the packet
2488 if (i == MAX_CHALLENGES)
2491 // check engine protocol
2492 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2494 if (developer.integer >= 10)
2495 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2496 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2500 // see if this is a duplicate connection request or a disconnected
2501 // client who is rejoining to the same client slot
2502 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2504 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2506 // this is a known client...
2507 if (client->spawned)
2509 // client crashed and is coming back,
2510 // keep their stuff intact
2511 if (developer.integer >= 10)
2512 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2513 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2515 SV_SendServerinfo(client);
2520 // client is still trying to connect,
2521 // so we send a duplicate reply
2522 if (developer.integer >= 10)
2523 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2524 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2530 if (NetConn_PreventConnectFlood(peeraddress))
2533 // find an empty client slot for this new client
2534 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2537 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2539 // allocated connection
2540 if (developer.integer >= 10)
2541 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2542 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2543 // now set up the client
2545 SV_ConnectClient(clientnum, conn);
2547 NetConn_Heartbeat(1);
2552 // no empty slots found - server is full
2553 if (developer.integer >= 10)
2554 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2555 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2559 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2561 const char *challenge = NULL;
2563 // If there was a challenge in the getinfo message
2564 if (length > 8 && string[7] == ' ')
2565 challenge = string + 8;
2567 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2569 if (developer.integer >= 10)
2570 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2571 NetConn_WriteString(mysocket, response, peeraddress);
2575 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2577 const char *challenge = NULL;
2579 // If there was a challenge in the getinfo message
2580 if (length > 10 && string[9] == ' ')
2581 challenge = string + 10;
2583 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2585 if (developer.integer >= 10)
2586 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2587 NetConn_WriteString(mysocket, response, peeraddress);
2591 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2593 char *password = string + 20;
2594 char *timeval = string + 37;
2595 char *s = strchr(timeval, ' ');
2596 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2597 const char *userlevel;
2599 return true; // invalid packet
2602 userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2603 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2606 if (length >= 5 && !memcmp(string, "rcon ", 5))
2609 char *s = string + 5;
2610 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2613 if(rcon_secure.integer)
2616 for (i = 0;!ISWHITESPACE(*s);s++)
2617 if (i < (int)sizeof(password) - 1)
2619 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2622 if (!ISWHITESPACE(password[0]))
2624 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2625 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2629 if (!strncmp(string, "ping", 4))
2631 if (developer.integer >= 10)
2632 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2633 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2636 if (!strncmp(string, "ack", 3))
2638 // we may not have liked the packet, but it was a command packet, so
2639 // we're done processing this packet now
2642 // netquake control packets, supported for compatibility only, and only
2643 // when running game protocols that are normally served via this connection
2645 // (this protects more modern protocols against being used for
2646 // Quake packet flood Denial Of Service attacks)
2647 if (length >= 5 && (i = BigLong(*((int *)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))
2651 const char *protocolname;
2654 SZ_Clear(&net_message);
2655 SZ_Write(&net_message, data, length);
2661 if (developer.integer >= 10)
2662 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2663 if(!islocal && sv_public.integer <= -2)
2666 protocolname = MSG_ReadString();
2667 protocolnumber = MSG_ReadByte();
2668 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2670 if (developer.integer >= 10)
2671 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2672 SZ_Clear(&net_message);
2673 // save space for the header, filled in later
2674 MSG_WriteLong(&net_message, 0);
2675 MSG_WriteByte(&net_message, CCREP_REJECT);
2676 MSG_WriteString(&net_message, "Incompatible version.\n");
2677 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2678 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2679 SZ_Clear(&net_message);
2683 // see if this connect request comes from a known client
2684 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2686 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2688 // this is either a duplicate connection request
2689 // or coming back from a timeout
2690 // (if so, keep their stuff intact)
2693 if (developer.integer >= 10)
2694 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2695 SZ_Clear(&net_message);
2696 // save space for the header, filled in later
2697 MSG_WriteLong(&net_message, 0);
2698 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2699 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2700 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2701 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2702 SZ_Clear(&net_message);
2704 // if client is already spawned, re-send the
2705 // serverinfo message as they'll need it to play
2706 if (client->spawned)
2709 SV_SendServerinfo(client);
2716 // this is a new client, check for connection flood
2717 if (NetConn_PreventConnectFlood(peeraddress))
2720 // find a slot for the new client
2721 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2724 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2726 // connect to the client
2727 // everything is allocated, just fill in the details
2728 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2729 if (developer.integer >= 10)
2730 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2731 // send back the info about the server connection
2732 SZ_Clear(&net_message);
2733 // save space for the header, filled in later
2734 MSG_WriteLong(&net_message, 0);
2735 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2736 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2737 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2738 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2739 SZ_Clear(&net_message);
2740 // now set up the client struct
2742 SV_ConnectClient(clientnum, conn);
2744 NetConn_Heartbeat(1);
2749 if (developer.integer >= 10)
2750 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2751 // no room; try to let player know
2752 SZ_Clear(&net_message);
2753 // save space for the header, filled in later
2754 MSG_WriteLong(&net_message, 0);
2755 MSG_WriteByte(&net_message, CCREP_REJECT);
2756 MSG_WriteString(&net_message, "Server is full.\n");
2757 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2758 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2759 SZ_Clear(&net_message);
2761 case CCREQ_SERVER_INFO:
2762 if (developer.integer >= 10)
2763 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2764 if(!islocal && sv_public.integer <= -1)
2766 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2769 char myaddressstring[128];
2770 if (developer.integer >= 10)
2771 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2772 SZ_Clear(&net_message);
2773 // save space for the header, filled in later
2774 MSG_WriteLong(&net_message, 0);
2775 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2776 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2777 MSG_WriteString(&net_message, myaddressstring);
2778 MSG_WriteString(&net_message, hostname.string);
2779 MSG_WriteString(&net_message, sv.name);
2780 // How many clients are there?
2781 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2782 if (svs.clients[i].active)
2784 MSG_WriteByte(&net_message, numclients);
2785 MSG_WriteByte(&net_message, svs.maxclients);
2786 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2787 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2788 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2789 SZ_Clear(&net_message);
2792 case CCREQ_PLAYER_INFO:
2793 if (developer.integer >= 10)
2794 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2795 if(!islocal && sv_public.integer <= -1)
2799 int playerNumber, activeNumber, clientNumber;
2802 playerNumber = MSG_ReadByte();
2804 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2805 if (client->active && ++activeNumber == playerNumber)
2807 if (clientNumber != svs.maxclients)
2809 SZ_Clear(&net_message);
2810 // save space for the header, filled in later
2811 MSG_WriteLong(&net_message, 0);
2812 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2813 MSG_WriteByte(&net_message, playerNumber);
2814 MSG_WriteString(&net_message, client->name);
2815 MSG_WriteLong(&net_message, client->colors);
2816 MSG_WriteLong(&net_message, client->frags);
2817 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2818 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2819 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2820 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2821 SZ_Clear(&net_message);
2825 case CCREQ_RULE_INFO:
2826 if (developer.integer >= 10)
2827 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2828 if(!islocal && sv_public.integer <= -1)
2835 // find the search start location
2836 prevCvarName = MSG_ReadString();
2837 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2839 // send the response
2840 SZ_Clear(&net_message);
2841 // save space for the header, filled in later
2842 MSG_WriteLong(&net_message, 0);
2843 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2846 MSG_WriteString(&net_message, var->name);
2847 MSG_WriteString(&net_message, var->string);
2849 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2850 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2851 SZ_Clear(&net_message);
2857 SZ_Clear(&net_message);
2858 // we may not have liked the packet, but it was a valid control
2859 // packet, so we're done processing this packet now
2864 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2867 SV_ReadClientMessage();
2875 void NetConn_ServerFrame(void)
2878 lhnetaddress_t peeraddress;
2879 for (i = 0;i < sv_numsockets;i++)
2880 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2881 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2882 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2884 // never timeout loopback connections
2885 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2887 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2889 SV_DropClient(false);
2895 void NetConn_SleepMicroseconds(int microseconds)
2897 LHNET_SleepUntilPacket_Microseconds(microseconds);
2900 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2904 lhnetaddress_t masteraddress;
2905 lhnetaddress_t broadcastaddress;
2908 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2911 // 26000 is the default quake server port, servers on other ports will not
2913 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2914 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2918 for (i = 0;i < cl_numsockets;i++)
2922 const char *cmdname, *extraoptions;
2923 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2925 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2927 // search LAN for Quake servers
2928 SZ_Clear(&net_message);
2929 // save space for the header, filled in later
2930 MSG_WriteLong(&net_message, 0);
2931 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2932 MSG_WriteString(&net_message, "QUAKE");
2933 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2934 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2935 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2936 SZ_Clear(&net_message);
2938 // search LAN for DarkPlaces servers
2939 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2942 // build the getservers message to send to the dpmaster master servers
2943 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
2945 cmdname = "getserversExt";
2946 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
2950 cmdname = "getservers";
2953 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
2956 for (masternum = 0;sv_masters[masternum].name;masternum++)
2958 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2961 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2965 // search favorite servers
2966 for(j = 0; j < nFavorites; ++j)
2968 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2970 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2971 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
2978 // only query QuakeWorld servers when the user wants to
2981 for (i = 0;i < cl_numsockets;i++)
2985 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2987 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2989 // search LAN for QuakeWorld servers
2990 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2992 // build the getservers message to send to the qwmaster master servers
2993 // note this has no -1 prefix, and the trailing nul byte is sent
2994 dpsnprintf(request, sizeof(request), "c\n");
2998 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3000 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3002 if (m_state != m_slist)
3004 char lookupstring[128];
3005 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3006 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3009 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3013 // search favorite servers
3014 for(j = 0; j < nFavorites; ++j)
3016 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3018 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3020 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3021 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3028 if (!masterquerycount)
3030 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3031 M_Update_Return_Reason("No network");
3035 void NetConn_Heartbeat(int priority)
3037 lhnetaddress_t masteraddress;
3039 lhnetsocket_t *mysocket;
3041 // if it's a state change (client connected), limit next heartbeat to no
3042 // more than 30 sec in the future
3043 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3044 nextheartbeattime = realtime + 30.0;
3046 // limit heartbeatperiod to 30 to 270 second range,
3047 // lower limit is to avoid abusing master servers with excess traffic,
3048 // upper limit is to avoid timing out on the master server (which uses
3050 if (sv_heartbeatperiod.value < 30)
3051 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3052 if (sv_heartbeatperiod.value > 270)
3053 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3055 // make advertising optional and don't advertise singleplayer games, and
3056 // only send a heartbeat as often as the admin wants
3057 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3059 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3060 for (masternum = 0;sv_masters[masternum].name;masternum++)
3061 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3062 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3066 static void Net_Heartbeat_f(void)
3069 NetConn_Heartbeat(2);
3071 Con_Print("No server running, can not heartbeat to master server.\n");
3074 void PrintStats(netconn_t *conn)
3076 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3077 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3079 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3082 void Net_Stats_f(void)
3085 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3086 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3087 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3088 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3089 Con_Printf("packetsSent = %i\n", packetsSent);
3090 Con_Printf("packetsReSent = %i\n", packetsReSent);
3091 Con_Printf("packetsReceived = %i\n", packetsReceived);
3092 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3093 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3094 Con_Print("connections =\n");
3095 for (conn = netconn_list;conn;conn = conn->next)
3099 void Net_Refresh_f(void)
3101 if (m_state != m_slist) {
3102 Con_Print("Sending new requests to master servers\n");
3103 ServerList_QueryList(false, true, false, true);
3104 Con_Print("Listening for replies...\n");
3106 ServerList_QueryList(false, true, false, false);
3109 void Net_Slist_f(void)
3111 ServerList_ResetMasks();
3112 serverlist_sortbyfield = SLIF_PING;
3113 serverlist_sortflags = 0;
3114 if (m_state != m_slist) {
3115 Con_Print("Sending requests to master servers\n");
3116 ServerList_QueryList(true, true, false, true);
3117 Con_Print("Listening for replies...\n");
3119 ServerList_QueryList(true, true, false, false);
3122 void Net_SlistQW_f(void)
3124 ServerList_ResetMasks();
3125 serverlist_sortbyfield = SLIF_PING;
3126 serverlist_sortflags = 0;
3127 if (m_state != m_slist) {
3128 Con_Print("Sending requests to master servers\n");
3129 ServerList_QueryList(true, false, true, true);
3130 serverlist_consoleoutput = true;
3131 Con_Print("Listening for replies...\n");
3133 ServerList_QueryList(true, false, true, false);
3136 void NetConn_Init(void)
3139 lhnetaddress_t tempaddress;
3140 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3141 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3142 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3143 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3144 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3145 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3146 Cvar_RegisterVariable(&rcon_restricted_password);
3147 Cvar_RegisterVariable(&rcon_restricted_commands);
3148 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3149 Cvar_RegisterVariable(&net_slist_queriespersecond);
3150 Cvar_RegisterVariable(&net_slist_queriesperframe);
3151 Cvar_RegisterVariable(&net_slist_timeout);
3152 Cvar_RegisterVariable(&net_slist_maxtries);
3153 Cvar_RegisterVariable(&net_slist_favorites);
3154 Cvar_RegisterVariable(&net_slist_pause);
3155 Cvar_RegisterVariable(&net_messagetimeout);
3156 Cvar_RegisterVariable(&net_connecttimeout);
3157 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3158 Cvar_RegisterVariable(&cl_netlocalping);
3159 Cvar_RegisterVariable(&cl_netpacketloss_send);
3160 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3161 Cvar_RegisterVariable(&hostname);
3162 Cvar_RegisterVariable(&developer_networking);
3163 Cvar_RegisterVariable(&cl_netport);
3164 Cvar_RegisterVariable(&sv_netport);
3165 Cvar_RegisterVariable(&net_address);
3166 Cvar_RegisterVariable(&net_address_ipv6);
3167 Cvar_RegisterVariable(&sv_public);
3168 Cvar_RegisterVariable(&sv_heartbeatperiod);
3169 for (i = 0;sv_masters[i].name;i++)
3170 Cvar_RegisterVariable(&sv_masters[i]);
3171 Cvar_RegisterVariable(&gameversion);
3172 Cvar_RegisterVariable(&gameversion_min);
3173 Cvar_RegisterVariable(&gameversion_max);
3174 // 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.
3175 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3177 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3179 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3180 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3183 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3185 // 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
3186 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3188 i = atoi(com_argv[i + 1]);
3189 if (i >= 0 && i < 65536)
3191 Con_Printf("-port option used, setting port cvar to %i\n", i);
3192 Cvar_SetValueQuick(&sv_netport, i);
3195 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3199 net_message.data = net_message_buf;
3200 net_message.maxsize = sizeof(net_message_buf);
3201 net_message.cursize = 0;
3205 void NetConn_Shutdown(void)
3207 NetConn_CloseClientPorts();
3208 NetConn_CloseServerPorts();