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_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
607 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
608 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
609 if (realtime > conn->cleartime)
613 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
618 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
622 // if this packet was supposedly choked, but we find ourselves sending one
623 // anyway, make sure the size counting starts at zero
624 // (this mostly happens on level changes and disconnects and such)
625 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
626 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
628 if (protocol == PROTOCOL_QUAKEWORLD)
631 qboolean sendreliable;
633 // note that it is ok to send empty messages to the qw server,
634 // otherwise it won't respond to us at all
636 sendreliable = false;
637 // if the remote side dropped the last reliable message, resend it
638 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
640 // if the reliable transmit buffer is empty, copy the current message out
641 if (!conn->sendMessageLength && conn->message.cursize)
643 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
644 conn->sendMessageLength = conn->message.cursize;
645 SZ_Clear(&conn->message); // clear the message buffer
646 conn->qw.reliable_sequence ^= 1;
649 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
650 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
651 // last received unreliable packet number, and last received reliable packet number (0 or 1)
652 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
654 conn->outgoing_unreliable_sequence++;
655 // client sends qport in every packet
656 if (conn == cls.netcon)
658 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
660 // also update cls.qw_outgoing_sequence
661 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
663 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
665 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
669 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
671 // add the reliable message if there is one
674 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
675 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
676 packetLen += conn->sendMessageLength;
677 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
680 // add the unreliable message if possible
681 if (packetLen + data->cursize <= 1400)
683 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
684 memcpy(sendbuffer + packetLen, data->data, data->cursize);
685 packetLen += data->cursize;
688 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
691 unreliableMessagesSent++;
693 totallen += packetLen + 28;
697 unsigned int packetLen;
698 unsigned int dataLen;
700 unsigned int *header;
702 // if a reliable message fragment has been lost, send it again
703 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
705 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
707 dataLen = conn->sendMessageLength;
712 dataLen = MAX_PACKETFRAGMENT;
716 packetLen = NET_HEADERSIZE + dataLen;
718 header = (unsigned int *)sendbuffer;
719 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
720 header[1] = BigLong(conn->nq.sendSequence - 1);
721 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
723 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
725 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
727 conn->lastSendTime = realtime;
731 totallen += packetLen + 28;
734 // if we have a new reliable message to send, do so
735 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
737 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
739 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
740 conn->message.overflowed = true;
744 if (developer_networking.integer && conn == cls.netcon)
746 Con_Print("client sending reliable message to server:\n");
747 SZ_HexDumpToConsole(&conn->message);
750 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
751 conn->sendMessageLength = conn->message.cursize;
752 SZ_Clear(&conn->message);
754 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
756 dataLen = conn->sendMessageLength;
761 dataLen = MAX_PACKETFRAGMENT;
765 packetLen = NET_HEADERSIZE + dataLen;
767 header = (unsigned int *)sendbuffer;
768 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
769 header[1] = BigLong(conn->nq.sendSequence);
770 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
772 conn->nq.sendSequence++;
774 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
776 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
778 conn->lastSendTime = realtime;
780 reliableMessagesSent++;
782 totallen += packetLen + 28;
785 // if we have an unreliable message to send, do so
788 packetLen = NET_HEADERSIZE + data->cursize;
790 if (packetLen > (int)sizeof(sendbuffer))
792 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
796 header = (unsigned int *)sendbuffer;
797 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
798 header[1] = BigLong(conn->outgoing_unreliable_sequence);
799 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
801 conn->outgoing_unreliable_sequence++;
803 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
805 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
808 unreliableMessagesSent++;
810 totallen += packetLen + 28;
814 // delay later packets to obey rate limit
815 if (conn->cleartime < realtime - 0.1)
816 conn->cleartime = realtime - 0.1;
817 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
818 if (conn->cleartime < realtime)
819 conn->cleartime = realtime;
824 qboolean NetConn_HaveClientPorts(void)
826 return !!cl_numsockets;
829 qboolean NetConn_HaveServerPorts(void)
831 return !!sv_numsockets;
834 void NetConn_CloseClientPorts(void)
836 for (;cl_numsockets > 0;cl_numsockets--)
837 if (cl_sockets[cl_numsockets - 1])
838 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
841 void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
843 lhnetaddress_t address;
846 char addressstring2[1024];
847 if (addressstring && addressstring[0])
848 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
850 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
853 if ((s = LHNET_OpenSocket_Connectionless(&address)))
855 cl_sockets[cl_numsockets++] = s;
856 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
857 Con_Printf("Client opened a socket on address %s\n", addressstring2);
861 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
862 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
866 Con_Printf("Client unable to parse address %s\n", addressstring);
869 void NetConn_OpenClientPorts(void)
872 NetConn_CloseClientPorts();
873 port = bound(0, cl_netport.integer, 65535);
874 if (cl_netport.integer != port)
875 Cvar_SetValueQuick(&cl_netport, port);
877 Con_Printf("Client using an automatically assigned port\n");
879 Con_Printf("Client using port %i\n", port);
880 NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
881 NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
882 NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
885 void NetConn_CloseServerPorts(void)
887 for (;sv_numsockets > 0;sv_numsockets--)
888 if (sv_sockets[sv_numsockets - 1])
889 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
892 qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
894 lhnetaddress_t address;
897 char addressstring2[1024];
900 for (port = defaultport; port <= defaultport + range; port++)
902 if (addressstring && addressstring[0])
903 success = LHNETADDRESS_FromString(&address, addressstring, port);
905 success = LHNETADDRESS_FromPort(&address, addresstype, port);
908 if ((s = LHNET_OpenSocket_Connectionless(&address)))
910 sv_sockets[sv_numsockets++] = s;
911 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
912 Con_Printf("Server listening on address %s\n", addressstring2);
917 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
918 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
923 Con_Printf("Server unable to parse address %s\n", addressstring);
924 // if it cant parse one address, it wont be able to parse another for sure
931 void NetConn_OpenServerPorts(int opennetports)
934 NetConn_CloseServerPorts();
935 NetConn_UpdateSockets();
936 port = bound(0, sv_netport.integer, 65535);
939 Con_Printf("Server using port %i\n", port);
940 if (sv_netport.integer != port)
941 Cvar_SetValueQuick(&sv_netport, port);
942 if (cls.state != ca_dedicated)
943 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
946 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
947 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
949 if (sv_numsockets == 0)
950 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
953 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
955 int i, a = LHNETADDRESS_GetAddressType(address);
956 for (i = 0;i < cl_numsockets;i++)
957 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
958 return cl_sockets[i];
962 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
964 int i, a = LHNETADDRESS_GetAddressType(address);
965 for (i = 0;i < sv_numsockets;i++)
966 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
967 return sv_sockets[i];
971 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
974 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
975 conn->mysocket = mysocket;
976 conn->peeraddress = *peeraddress;
977 conn->lastMessageTime = realtime;
978 conn->message.data = conn->messagedata;
979 conn->message.maxsize = sizeof(conn->messagedata);
980 conn->message.cursize = 0;
981 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
982 // reduce effectiveness of connection request floods
983 conn->timeout = realtime + net_connecttimeout.value;
984 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
985 conn->next = netconn_list;
990 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
991 void NetConn_Close(netconn_t *conn)
994 // remove connection from list
996 // allow the client to reconnect immediately
997 NetConn_ClearConnectFlood(&(conn->peeraddress));
999 if (conn == netconn_list)
1000 netconn_list = conn->next;
1003 for (c = netconn_list;c;c = c->next)
1005 if (c->next == conn)
1007 c->next = conn->next;
1011 // not found in list, we'll avoid crashing here...
1019 static int clientport = -1;
1020 static int clientport2 = -1;
1021 static int hostport = -1;
1022 void NetConn_UpdateSockets(void)
1024 if (cls.state != ca_dedicated)
1026 if (clientport2 != cl_netport.integer)
1028 clientport2 = cl_netport.integer;
1029 if (cls.state == ca_connected)
1030 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1032 if (cls.state == ca_disconnected && clientport != clientport2)
1034 clientport = clientport2;
1035 NetConn_CloseClientPorts();
1037 if (cl_numsockets == 0)
1038 NetConn_OpenClientPorts();
1041 if (hostport != sv_netport.integer)
1043 hostport = sv_netport.integer;
1045 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1049 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1051 int originallength = length;
1055 if (protocol == PROTOCOL_QUAKEWORLD)
1057 int sequence, sequence_ack;
1058 int reliable_ack, reliable_message;
1062 sequence = LittleLong(*((int *)(data + 0)));
1063 sequence_ack = LittleLong(*((int *)(data + 4)));
1067 if (conn != cls.netcon)
1072 // 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?)
1073 qport = LittleShort(*((int *)(data + 8)));
1079 reliable_message = (sequence >> 31) & 1;
1080 reliable_ack = (sequence_ack >> 31) & 1;
1081 sequence &= ~(1<<31);
1082 sequence_ack &= ~(1<<31);
1083 if (sequence <= conn->qw.incoming_sequence)
1085 //Con_DPrint("Got a stale datagram\n");
1088 count = sequence - (conn->qw.incoming_sequence + 1);
1091 droppedDatagrams += count;
1092 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1095 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1096 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1097 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1098 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1101 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1102 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1103 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1104 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1105 if (reliable_ack == conn->qw.reliable_sequence)
1107 // received, now we will be able to send another reliable message
1108 conn->sendMessageLength = 0;
1109 reliableMessagesReceived++;
1111 conn->qw.incoming_sequence = sequence;
1112 if (conn == cls.netcon)
1113 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1114 conn->qw.incoming_acknowledged = sequence_ack;
1115 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1116 if (reliable_message)
1117 conn->qw.incoming_reliable_sequence ^= 1;
1118 conn->lastMessageTime = realtime;
1119 conn->timeout = realtime + newtimeout;
1120 unreliableMessagesReceived++;
1121 SZ_Clear(&net_message);
1122 SZ_Write(&net_message, data, length);
1130 unsigned int sequence;
1133 qlength = (unsigned int)BigLong(((int *)data)[0]);
1134 flags = qlength & ~NETFLAG_LENGTH_MASK;
1135 qlength &= NETFLAG_LENGTH_MASK;
1136 // control packets were already handled
1137 if (!(flags & NETFLAG_CTL) && qlength == length)
1139 sequence = BigLong(((int *)data)[1]);
1143 if (flags & NETFLAG_UNRELIABLE)
1145 if (sequence >= conn->nq.unreliableReceiveSequence)
1147 if (sequence > conn->nq.unreliableReceiveSequence)
1149 count = sequence - conn->nq.unreliableReceiveSequence;
1150 droppedDatagrams += count;
1151 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1154 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1155 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1156 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1157 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1160 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1161 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1162 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1163 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1164 conn->nq.unreliableReceiveSequence = sequence + 1;
1165 conn->lastMessageTime = realtime;
1166 conn->timeout = realtime + newtimeout;
1167 unreliableMessagesReceived++;
1170 SZ_Clear(&net_message);
1171 SZ_Write(&net_message, data, length);
1177 // Con_DPrint("Got a stale datagram\n");
1180 else if (flags & NETFLAG_ACK)
1182 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1183 if (sequence == (conn->nq.sendSequence - 1))
1185 if (sequence == conn->nq.ackSequence)
1187 conn->nq.ackSequence++;
1188 if (conn->nq.ackSequence != conn->nq.sendSequence)
1189 Con_DPrint("ack sequencing error\n");
1190 conn->lastMessageTime = realtime;
1191 conn->timeout = realtime + newtimeout;
1192 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1194 unsigned int packetLen;
1195 unsigned int dataLen;
1197 unsigned int *header;
1199 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1200 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1202 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1204 dataLen = conn->sendMessageLength;
1209 dataLen = MAX_PACKETFRAGMENT;
1213 packetLen = NET_HEADERSIZE + dataLen;
1215 header = (unsigned int *)sendbuffer;
1216 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1217 header[1] = BigLong(conn->nq.sendSequence);
1218 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1220 conn->nq.sendSequence++;
1222 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1224 conn->lastSendTime = realtime;
1229 conn->sendMessageLength = 0;
1232 // Con_DPrint("Duplicate ACK received\n");
1235 // Con_DPrint("Stale ACK received\n");
1238 else if (flags & NETFLAG_DATA)
1240 unsigned int temppacket[2];
1241 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1242 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1243 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1244 temppacket[1] = BigLong(sequence);
1245 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1246 if (sequence == conn->nq.receiveSequence)
1248 conn->lastMessageTime = realtime;
1249 conn->timeout = realtime + newtimeout;
1250 conn->nq.receiveSequence++;
1251 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1252 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1253 conn->receiveMessageLength += length;
1255 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1256 "Dropping the message!\n", sequence );
1257 conn->receiveMessageLength = 0;
1260 if (flags & NETFLAG_EOM)
1262 reliableMessagesReceived++;
1263 length = conn->receiveMessageLength;
1264 conn->receiveMessageLength = 0;
1267 SZ_Clear(&net_message);
1268 SZ_Write(&net_message, conn->receiveMessage, length);
1275 receivedDuplicateCount++;
1283 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1285 cls.connect_trying = false;
1286 M_Update_Return_Reason("");
1287 // the connection request succeeded, stop current connection and set up a new connection
1289 // if we're connecting to a remote server, shut down any local server
1290 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1291 Host_ShutdownServer ();
1292 // allocate a net connection to keep track of things
1293 cls.netcon = NetConn_Open(mysocket, peeraddress);
1294 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1295 key_dest = key_game;
1297 cls.demonum = -1; // not in the demo loop now
1298 cls.state = ca_connected;
1299 cls.signon = 0; // need all the signon messages before playing
1300 cls.protocol = initialprotocol;
1301 // reset move sequence numbering on this new connection
1302 cls.servermovesequence = 0;
1303 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1304 Cmd_ForwardStringToServer("new");
1305 if (cls.protocol == PROTOCOL_QUAKE)
1307 // write a keepalive (clc_nop) as it seems to greatly improve the
1308 // chances of connecting to a netquake server
1310 unsigned char buf[4];
1311 memset(&msg, 0, sizeof(msg));
1313 msg.maxsize = sizeof(buf);
1314 MSG_WriteChar(&msg, clc_nop);
1315 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1319 int NetConn_IsLocalGame(void)
1321 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1326 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1330 serverlist_entry_t *entry = NULL;
1332 // search the cache for this server and update it
1333 for (n = 0;n < serverlist_cachecount;n++) {
1334 entry = &serverlist_cache[ n ];
1335 if (!strcmp(addressstring, entry->info.cname))
1339 if (n == serverlist_cachecount)
1341 // LAN search doesnt require an answer from the master server so we wont
1342 // know the ping nor will it be initialized already...
1345 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1348 entry = &serverlist_cache[n];
1350 memset(entry, 0, sizeof(*entry));
1351 // store the data the engine cares about (address and ping)
1352 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1353 entry->info.ping = 100000;
1354 entry->querytime = realtime;
1355 // if not in the slist menu we should print the server to console
1356 if (serverlist_consoleoutput)
1357 Con_Printf("querying %s\n", addressstring);
1358 ++serverlist_cachecount;
1360 // if this is the first reply from this server, count it as having replied
1361 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1362 pingtime = bound(0, pingtime, 9999);
1363 if (entry->query == SQS_REFRESHING) {
1364 entry->info.ping = pingtime;
1365 entry->query = SQS_QUERIED;
1367 // convert to unsigned to catch the -1
1368 // 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]
1369 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1373 // other server info is updated by the caller
1377 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1379 serverlist_entry_t *entry = &serverlist_cache[n];
1380 serverlist_info_t *info = &entry->info;
1381 // update description strings for engine menu and console output
1382 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);
1383 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1385 info->gameversion != gameversion.integer
1388 gameversion_min.integer >= 0 // min/max range set by user/mod?
1389 && gameversion_max.integer >= 0
1390 && gameversion_min.integer >= info->gameversion // version of server in min/max range?
1391 && gameversion_max.integer <= info->gameversion
1394 info->mod, info->map);
1395 if (entry->query == SQS_QUERIED)
1397 if(!serverlist_paused)
1398 ServerList_ViewList_Remove(entry);
1400 // if not in the slist menu we should print the server to console (if wanted)
1401 else if( serverlist_consoleoutput )
1402 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1403 // and finally, update the view set
1404 if(!serverlist_paused)
1405 ServerList_ViewList_Insert( entry );
1406 // update the entry's state
1407 serverlist_cache[n].query = SQS_QUERIED;
1410 // returns true, if it's sensible to continue the processing
1411 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1413 serverlist_entry_t *entry;
1415 // ignore the rest of the message if the serverlist is full
1416 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1418 // also ignore it if we have already queried it (other master server response)
1419 for( n = 0 ; n < serverlist_cachecount ; n++ )
1420 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1423 entry = &serverlist_cache[n];
1425 if( n < serverlist_cachecount ) {
1426 // the entry has already been queried once or
1430 memset(entry, 0, sizeof(entry));
1431 entry->protocol = protocol;
1432 // store the data the engine cares about (address and ping)
1433 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1435 entry->info.isfavorite = isfavorite;
1437 // no, then reset the ping right away
1438 entry->info.ping = -1;
1439 // we also want to increase the serverlist_cachecount then
1440 serverlist_cachecount++;
1443 entry->query = SQS_QUERYING;
1448 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1451 if (serverlist_consoleoutput)
1452 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1455 char ipstring [128];
1458 if (data[0] == '\\')
1460 unsigned short port = data[5] * 256 + data[6];
1462 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1463 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1465 // move on to next address in packet
1470 else if (data[0] == '/' && isextended && length >= 19)
1472 unsigned short port = data[17] * 256 + data[18];
1478 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1480 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1483 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1484 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1485 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1490 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1491 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1492 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1497 // move on to next address in packet
1503 Con_Print("Error while parsing the server list\n");
1507 if (serverlist_consoleoutput && developer_networking.integer)
1508 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1510 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1516 // begin or resume serverlist queries
1517 serverlist_querysleep = false;
1518 serverlist_querywaittime = realtime + 3;
1521 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1523 qboolean fromserver;
1524 int ret, c, control;
1526 char *string, addressstring2[128], ipstring[32];
1527 char stringbuf[16384];
1529 // quakeworld ingame packet
1530 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1532 // convert the address to a string incase we need it
1533 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1535 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1537 // received a command string - strip off the packaging and put it
1538 // into our string buffer with NULL termination
1541 length = min(length, (int)sizeof(stringbuf) - 1);
1542 memcpy(stringbuf, data, length);
1543 stringbuf[length] = 0;
1546 if (developer_networking.integer)
1548 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1549 Com_HexDumpToConsole(data, length);
1552 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1554 // darkplaces or quake3
1555 char protocolnames[1400];
1556 Protocol_Names(protocolnames, sizeof(protocolnames));
1557 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1558 M_Update_Return_Reason("Got challenge response");
1559 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1560 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1561 // TODO: add userinfo stuff here instead of using NQ commands?
1562 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1565 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1567 // darkplaces or quake3
1568 M_Update_Return_Reason("Accepted");
1569 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1572 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1574 char rejectreason[32];
1575 cls.connect_trying = false;
1577 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1578 memcpy(rejectreason, string, length);
1579 rejectreason[length] = 0;
1580 M_Update_Return_Reason(rejectreason);
1583 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1585 serverlist_info_t *info;
1590 // search the cache for this server and update it
1591 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1595 info = &serverlist_cache[n].info;
1600 info->qcstatus[0] = 0;
1601 info->players[0] = 0;
1602 info->protocol = -1;
1603 info->numplayers = 0;
1605 info->maxplayers = 0;
1606 info->gameversion = 0;
1608 p = strchr(string, '\n');
1611 *p = 0; // cut off the string there
1615 Con_Printf("statusResponse without players block?\n");
1617 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1618 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1619 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1620 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1621 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1622 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1623 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1624 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1625 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1626 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1627 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1628 info->numhumans = info->numplayers - max(0, info->numbots);
1629 info->freeslots = info->maxplayers - info->numplayers;
1631 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1635 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1637 serverlist_info_t *info;
1641 // search the cache for this server and update it
1642 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1646 info = &serverlist_cache[n].info;
1651 info->qcstatus[0] = 0;
1652 info->players[0] = 0;
1653 info->protocol = -1;
1654 info->numplayers = 0;
1656 info->maxplayers = 0;
1657 info->gameversion = 0;
1659 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1660 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1661 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1662 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1663 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1664 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1665 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1666 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1667 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1668 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1669 info->numhumans = info->numplayers - max(0, info->numbots);
1670 info->freeslots = info->maxplayers - info->numplayers;
1672 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1676 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1678 // Extract the IP addresses
1681 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1684 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1686 // Extract the IP addresses
1689 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1692 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1694 // Extract the IP addresses
1698 if (serverlist_consoleoutput)
1699 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1700 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1702 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1703 if (serverlist_consoleoutput && developer_networking.integer)
1704 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1706 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1710 // move on to next address in packet
1714 // begin or resume serverlist queries
1715 serverlist_querysleep = false;
1716 serverlist_querywaittime = realtime + 3;
1719 if (!strncmp(string, "extResponse ", 12))
1721 ++net_extresponse_count;
1722 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1723 net_extresponse_count = NET_EXTRESPONSE_MAX;
1724 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1725 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1728 if (!strncmp(string, "ping", 4))
1730 if (developer.integer >= 10)
1731 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1732 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1735 if (!strncmp(string, "ack", 3))
1737 // QuakeWorld compatibility
1738 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1740 // challenge message
1741 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1742 M_Update_Return_Reason("Got QuakeWorld challenge response");
1743 cls.qw_qport = qport.integer;
1744 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1745 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1746 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1749 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1752 M_Update_Return_Reason("QuakeWorld Accepted");
1753 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1756 if (length > 2 && !memcmp(string, "n\\", 2))
1758 serverlist_info_t *info;
1762 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1763 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1766 // search the cache for this server and update it
1767 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1771 info = &serverlist_cache[n].info;
1772 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1773 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1774 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1775 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1777 info->numplayers = 0; // updated below
1778 info->numhumans = 0; // updated below
1779 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1780 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1782 // count active players on server
1783 // (we could gather more info, but we're just after the number)
1784 s = strchr(string, '\n');
1788 while (s < string + length)
1790 for (;s < string + length && *s != '\n';s++)
1792 if (s >= string + length)
1800 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1804 if (string[0] == 'n')
1807 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1809 // we may not have liked the packet, but it was a command packet, so
1810 // we're done processing this packet now
1813 // quakeworld ingame packet
1814 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1817 CL_ParseServerMessage();
1820 // netquake control packets, supported for compatibility only
1821 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1824 serverlist_info_t *info;
1828 SZ_Clear(&net_message);
1829 SZ_Write(&net_message, data, length);
1835 if (developer.integer >= 10)
1836 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1837 if (cls.connect_trying)
1839 lhnetaddress_t clientportaddress;
1840 clientportaddress = *peeraddress;
1841 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1842 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1843 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1844 M_Update_Return_Reason("Accepted");
1845 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1849 if (developer.integer >= 10)
1850 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1851 cls.connect_trying = false;
1852 M_Update_Return_Reason((char *)MSG_ReadString());
1854 case CCREP_SERVER_INFO:
1855 if (developer.integer >= 10)
1856 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1857 // LordHavoc: because the quake server may report weird addresses
1858 // we just ignore it and keep the real address
1860 // search the cache for this server and update it
1861 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1865 info = &serverlist_cache[n].info;
1866 strlcpy(info->game, "Quake", sizeof(info->game));
1867 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1868 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1869 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1870 info->numplayers = MSG_ReadByte();
1871 info->maxplayers = MSG_ReadByte();
1872 info->protocol = MSG_ReadByte();
1874 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1877 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1878 if (developer.integer >= 10)
1879 Con_Printf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1881 Con_Printf("%s\n", MSG_ReadString());
1883 case CCREP_PLAYER_INFO:
1884 // we got a CCREP_PLAYER_INFO??
1885 //if (developer.integer >= 10)
1886 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1888 case CCREP_RULE_INFO:
1889 // we got a CCREP_RULE_INFO??
1890 //if (developer.integer >= 10)
1891 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1896 SZ_Clear(&net_message);
1897 // we may not have liked the packet, but it was a valid control
1898 // packet, so we're done processing this packet now
1902 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1903 CL_ParseServerMessage();
1907 void NetConn_QueryQueueFrame(void)
1913 static double querycounter = 0;
1915 if(!net_slist_pause.integer && serverlist_paused)
1916 ServerList_RebuildViewList();
1917 serverlist_paused = net_slist_pause.integer;
1919 if (serverlist_querysleep)
1922 // apply a cool down time after master server replies,
1923 // to avoid messing up the ping times on the servers
1924 if (serverlist_querywaittime > realtime)
1927 // each time querycounter reaches 1.0 issue a query
1928 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1929 maxqueries = (int)querycounter;
1930 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1931 querycounter -= maxqueries;
1933 if( maxqueries == 0 ) {
1937 // scan serverlist and issue queries as needed
1938 serverlist_querysleep = true;
1940 timeouttime = realtime - net_slist_timeout.value;
1941 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1943 serverlist_entry_t *entry = &serverlist_cache[ index ];
1944 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1949 serverlist_querysleep = false;
1950 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1955 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1957 lhnetaddress_t address;
1960 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1961 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1963 for (socket = 0; socket < cl_numsockets ; socket++)
1964 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1968 for (socket = 0; socket < cl_numsockets ; socket++)
1969 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1972 // update the entry fields
1973 entry->querytime = realtime;
1974 entry->querycounter++;
1976 // if not in the slist menu we should print the server to console
1977 if (serverlist_consoleoutput)
1978 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1984 // have we tried to refresh this server?
1985 if( entry->query == SQS_REFRESHING ) {
1986 // yes, so update the reply count (since its not responding anymore)
1988 if(!serverlist_paused)
1989 ServerList_ViewList_Remove(entry);
1991 entry->query = SQS_TIMEDOUT;
1996 void NetConn_ClientFrame(void)
1999 lhnetaddress_t peeraddress;
2000 NetConn_UpdateSockets();
2001 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2003 if (cls.connect_remainingtries == 0)
2004 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2005 cls.connect_nextsendtime = realtime + 1;
2006 cls.connect_remainingtries--;
2007 if (cls.connect_remainingtries <= -10)
2009 cls.connect_trying = false;
2010 M_Update_Return_Reason("Connect: Failed");
2013 // try challenge first (newer DP server or QW)
2014 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2015 // then try netquake as a fallback (old server, or netquake)
2016 SZ_Clear(&net_message);
2017 // save space for the header, filled in later
2018 MSG_WriteLong(&net_message, 0);
2019 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2020 MSG_WriteString(&net_message, "QUAKE");
2021 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2022 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2023 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2024 SZ_Clear(&net_message);
2026 for (i = 0;i < cl_numsockets;i++)
2027 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2028 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2029 NetConn_QueryQueueFrame();
2030 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2032 Con_Print("Connection timed out\n");
2034 Host_ShutdownServer ();
2038 #define MAX_CHALLENGES 128
2041 lhnetaddress_t address;
2045 challenge[MAX_CHALLENGES];
2047 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2051 for (i = 0;i < bufferlength - 1;i++)
2055 c = rand () % (127 - 33) + 33;
2056 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2062 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2063 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2066 unsigned int nb_clients = 0, nb_bots = 0, i;
2072 // How many clients are there?
2073 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2075 if (svs.clients[i].active)
2078 if (!svs.clients[i].netconnection)
2084 if(prog->globaloffsets.worldstatus >= 0)
2086 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2092 for(q = str; *q; ++q)
2093 if(*q != '\\' && *q != '\n')
2099 /// \TODO: we should add more information for the full status string
2100 length = dpsnprintf(out_msg, out_size,
2101 "\377\377\377\377%s\x0A"
2102 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2103 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2107 fullstatus ? "statusResponse" : "infoResponse",
2108 gamename, com_modname, gameversion.integer, svs.maxclients,
2109 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2110 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2111 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2112 fullstatus ? "\n" : "");
2114 // Make sure it fits in the buffer
2124 savelength = length;
2126 ptr = out_msg + length;
2127 left = (int)out_size - length;
2129 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2131 client_t *cl = &svs.clients[i];
2134 int nameind, cleanind, pingvalue;
2136 char cleanname [sizeof(cl->name)];
2138 // Remove all characters '"' and '\' in the player name
2143 curchar = cl->name[nameind++];
2144 if (curchar != '"' && curchar != '\\')
2146 cleanname[cleanind++] = curchar;
2147 if (cleanind == sizeof(cleanname) - 1)
2150 } while (curchar != '\0');
2151 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2153 pingvalue = (int)(cl->ping * 1000.0f);
2154 if(cl->netconnection)
2155 pingvalue = bound(1, pingvalue, 9999);
2160 if(prog->fieldoffsets.clientstatus >= 0)
2162 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2168 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2169 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2175 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2177 if(cl->frags == -666) // spectator
2178 strlcpy(teambuf, " 0", sizeof(teambuf));
2179 else if(cl->colors == 0x44) // red team
2180 strlcpy(teambuf, " 1", sizeof(teambuf));
2181 else if(cl->colors == 0xDD) // blue team
2182 strlcpy(teambuf, " 2", sizeof(teambuf));
2183 else if(cl->colors == 0xCC) // yellow team
2184 strlcpy(teambuf, " 3", sizeof(teambuf));
2185 else if(cl->colors == 0x99) // pink team
2186 strlcpy(teambuf, " 4", sizeof(teambuf));
2188 strlcpy(teambuf, " 0", sizeof(teambuf));
2193 // note: team number is inserted according to SoF2 protocol
2195 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2201 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2210 // turn it into an infoResponse!
2211 out_msg[savelength] = 0;
2212 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2213 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2230 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2232 int floodslotnum, bestfloodslotnum;
2233 double bestfloodtime;
2234 lhnetaddress_t noportpeeraddress;
2235 // see if this is a connect flood
2236 noportpeeraddress = *peeraddress;
2237 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2238 bestfloodslotnum = 0;
2239 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2240 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2242 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2244 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2245 bestfloodslotnum = floodslotnum;
2247 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2249 // this address matches an ongoing flood address
2250 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2252 // renew the ban on this address so it does not expire
2253 // until the flood has subsided
2254 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2255 //Con_Printf("Flood detected!\n");
2258 // the flood appears to have subsided, so allow this
2259 bestfloodslotnum = floodslotnum; // reuse the same slot
2263 // begin a new timeout on this address
2264 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2265 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2266 //Con_Printf("Flood detection initiated!\n");
2270 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2273 lhnetaddress_t noportpeeraddress;
2274 // see if this is a connect flood
2275 noportpeeraddress = *peeraddress;
2276 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2277 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2279 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2281 // this address matches an ongoing flood address
2283 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2284 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2285 //Con_Printf("Flood cleared!\n");
2290 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2292 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2297 t1 = (long) time(NULL);
2298 t2 = strtol(s, NULL, 0);
2299 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2302 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2305 return !memcmp(mdfourbuf, hash, 16);
2308 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2310 return !strcmp(password, hash);
2313 /// returns a string describing the user level, or NULL for auth failure
2314 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2319 if(comparator(rcon_password.string, password, cs, cslen))
2322 if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2325 for(text = s; text != endpos; ++text)
2326 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2327 return NULL; // block possible exploits against the parser/alias expansion
2331 size_t l = strlen(s);
2334 hasquotes = (strchr(s, '"') != NULL);
2335 // sorry, we can't allow these substrings in wildcard expressions,
2336 // as they can mess with the argument counts
2337 text = rcon_restricted_commands.string;
2338 while(COM_ParseToken_Console(&text))
2340 // com_token now contains a pattern to check for...
2341 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2344 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2347 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2349 if(!strcmp(com_token, s))
2352 else // single-arg expression? must match the beginning of the command
2354 if(!strcmp(com_token, s))
2356 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2360 // if we got here, nothing matched!
2367 return "restricted rcon";
2370 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2374 // looks like a legitimate rcon command with the correct password
2375 const char *s_ptr = s;
2376 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2377 while(s_ptr != endpos)
2379 size_t l = strlen(s_ptr);
2381 Con_Printf(" %s;", s_ptr);
2386 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2387 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2390 size_t l = strlen(s);
2393 client_t *host_client_save = host_client;
2394 Cmd_ExecuteString(s, src_command);
2395 host_client = host_client_save;
2396 // in case it is a command that changes host_client (like restart)
2400 Con_Rcon_Redirect_End();
2404 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2408 extern void SV_SendServerinfo (client_t *client);
2409 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2411 int i, ret, clientnum, best;
2414 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2415 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2420 // convert the address to a string incase we need it
2421 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2423 // see if we can identify the sender as a local player
2424 // (this is necessary for rcon to send a reliable reply if the client is
2425 // actually on the server, not sending remotely)
2426 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2427 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2429 if (i == svs.maxclients)
2432 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2434 // received a command string - strip off the packaging and put it
2435 // into our string buffer with NULL termination
2438 length = min(length, (int)sizeof(stringbuf) - 1);
2439 memcpy(stringbuf, data, length);
2440 stringbuf[length] = 0;
2443 if (developer.integer >= 10)
2445 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2446 Com_HexDumpToConsole(data, length);
2449 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2451 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2453 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2455 if (besttime > challenge[i].time)
2456 besttime = challenge[best = i].time;
2458 // if we did not find an exact match, choose the oldest and
2459 // update address and string
2460 if (i == MAX_CHALLENGES)
2463 challenge[i].address = *peeraddress;
2464 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2466 challenge[i].time = realtime;
2467 // send the challenge
2468 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2471 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2476 if (!(s = SearchInfostring(string, "challenge")))
2478 // validate the challenge
2479 for (i = 0;i < MAX_CHALLENGES;i++)
2480 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2482 // if the challenge is not recognized, drop the packet
2483 if (i == MAX_CHALLENGES)
2486 // check engine protocol
2487 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2489 if (developer.integer >= 10)
2490 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2491 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2495 // see if this is a duplicate connection request or a disconnected
2496 // client who is rejoining to the same client slot
2497 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2499 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2501 // this is a known client...
2502 if (client->spawned)
2504 // client crashed and is coming back,
2505 // keep their stuff intact
2506 if (developer.integer >= 10)
2507 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2508 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2510 SV_SendServerinfo(client);
2515 // client is still trying to connect,
2516 // so we send a duplicate reply
2517 if (developer.integer >= 10)
2518 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2519 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2525 if (NetConn_PreventConnectFlood(peeraddress))
2528 // find an empty client slot for this new client
2529 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2532 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2534 // allocated connection
2535 if (developer.integer >= 10)
2536 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2537 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2538 // now set up the client
2540 SV_ConnectClient(clientnum, conn);
2542 NetConn_Heartbeat(1);
2547 // no empty slots found - server is full
2548 if (developer.integer >= 10)
2549 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2550 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2554 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2556 const char *challenge = NULL;
2558 // If there was a challenge in the getinfo message
2559 if (length > 8 && string[7] == ' ')
2560 challenge = string + 8;
2562 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2564 if (developer.integer >= 10)
2565 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2566 NetConn_WriteString(mysocket, response, peeraddress);
2570 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2572 const char *challenge = NULL;
2574 // If there was a challenge in the getinfo message
2575 if (length > 10 && string[9] == ' ')
2576 challenge = string + 10;
2578 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2580 if (developer.integer >= 10)
2581 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2582 NetConn_WriteString(mysocket, response, peeraddress);
2586 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2588 char *password = string + 20;
2589 char *timeval = string + 37;
2590 char *s = strchr(timeval, ' ');
2591 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2592 const char *userlevel;
2594 return true; // invalid packet
2597 userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2598 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2601 if (length >= 5 && !memcmp(string, "rcon ", 5))
2604 char *s = string + 5;
2605 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2608 if(rcon_secure.integer)
2611 for (i = 0;!ISWHITESPACE(*s);s++)
2612 if (i < (int)sizeof(password) - 1)
2614 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2617 if (!ISWHITESPACE(password[0]))
2619 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2620 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2624 if (!strncmp(string, "ping", 4))
2626 if (developer.integer >= 10)
2627 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2628 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2631 if (!strncmp(string, "ack", 3))
2633 // we may not have liked the packet, but it was a command packet, so
2634 // we're done processing this packet now
2637 // netquake control packets, supported for compatibility only, and only
2638 // when running game protocols that are normally served via this connection
2640 // (this protects more modern protocols against being used for
2641 // Quake packet flood Denial Of Service attacks)
2642 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))
2646 const char *protocolname;
2649 SZ_Clear(&net_message);
2650 SZ_Write(&net_message, data, length);
2656 if (developer.integer >= 10)
2657 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2658 if(!islocal && sv_public.integer <= -2)
2661 protocolname = MSG_ReadString();
2662 protocolnumber = MSG_ReadByte();
2663 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2665 if (developer.integer >= 10)
2666 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2667 SZ_Clear(&net_message);
2668 // save space for the header, filled in later
2669 MSG_WriteLong(&net_message, 0);
2670 MSG_WriteByte(&net_message, CCREP_REJECT);
2671 MSG_WriteString(&net_message, "Incompatible version.\n");
2672 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2673 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2674 SZ_Clear(&net_message);
2678 // see if this connect request comes from a known client
2679 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2681 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2683 // this is either a duplicate connection request
2684 // or coming back from a timeout
2685 // (if so, keep their stuff intact)
2688 if (developer.integer >= 10)
2689 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2690 SZ_Clear(&net_message);
2691 // save space for the header, filled in later
2692 MSG_WriteLong(&net_message, 0);
2693 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2694 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2695 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2696 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2697 SZ_Clear(&net_message);
2699 // if client is already spawned, re-send the
2700 // serverinfo message as they'll need it to play
2701 if (client->spawned)
2704 SV_SendServerinfo(client);
2711 // this is a new client, check for connection flood
2712 if (NetConn_PreventConnectFlood(peeraddress))
2715 // find a slot for the new client
2716 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2719 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2721 // connect to the client
2722 // everything is allocated, just fill in the details
2723 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2724 if (developer.integer >= 10)
2725 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2726 // send back the info about the server connection
2727 SZ_Clear(&net_message);
2728 // save space for the header, filled in later
2729 MSG_WriteLong(&net_message, 0);
2730 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2731 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2732 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2733 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2734 SZ_Clear(&net_message);
2735 // now set up the client struct
2737 SV_ConnectClient(clientnum, conn);
2739 NetConn_Heartbeat(1);
2744 if (developer.integer >= 10)
2745 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2746 // no room; try to let player know
2747 SZ_Clear(&net_message);
2748 // save space for the header, filled in later
2749 MSG_WriteLong(&net_message, 0);
2750 MSG_WriteByte(&net_message, CCREP_REJECT);
2751 MSG_WriteString(&net_message, "Server is full.\n");
2752 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2753 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2754 SZ_Clear(&net_message);
2756 case CCREQ_SERVER_INFO:
2757 if (developer.integer >= 10)
2758 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2759 if(!islocal && sv_public.integer <= -1)
2761 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2764 char myaddressstring[128];
2765 if (developer.integer >= 10)
2766 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2767 SZ_Clear(&net_message);
2768 // save space for the header, filled in later
2769 MSG_WriteLong(&net_message, 0);
2770 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2771 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2772 MSG_WriteString(&net_message, myaddressstring);
2773 MSG_WriteString(&net_message, hostname.string);
2774 MSG_WriteString(&net_message, sv.name);
2775 // How many clients are there?
2776 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2777 if (svs.clients[i].active)
2779 MSG_WriteByte(&net_message, numclients);
2780 MSG_WriteByte(&net_message, svs.maxclients);
2781 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2782 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2783 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2784 SZ_Clear(&net_message);
2787 case CCREQ_PLAYER_INFO:
2788 if (developer.integer >= 10)
2789 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2790 if(!islocal && sv_public.integer <= -1)
2794 int playerNumber, activeNumber, clientNumber;
2797 playerNumber = MSG_ReadByte();
2799 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2800 if (client->active && ++activeNumber == playerNumber)
2802 if (clientNumber != svs.maxclients)
2804 SZ_Clear(&net_message);
2805 // save space for the header, filled in later
2806 MSG_WriteLong(&net_message, 0);
2807 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2808 MSG_WriteByte(&net_message, playerNumber);
2809 MSG_WriteString(&net_message, client->name);
2810 MSG_WriteLong(&net_message, client->colors);
2811 MSG_WriteLong(&net_message, client->frags);
2812 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2813 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2814 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2815 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2816 SZ_Clear(&net_message);
2820 case CCREQ_RULE_INFO:
2821 if (developer.integer >= 10)
2822 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2823 if(!islocal && sv_public.integer <= -1)
2830 // find the search start location
2831 prevCvarName = MSG_ReadString();
2832 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2834 // send the response
2835 SZ_Clear(&net_message);
2836 // save space for the header, filled in later
2837 MSG_WriteLong(&net_message, 0);
2838 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2841 MSG_WriteString(&net_message, var->name);
2842 MSG_WriteString(&net_message, var->string);
2844 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2845 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2846 SZ_Clear(&net_message);
2852 SZ_Clear(&net_message);
2853 // we may not have liked the packet, but it was a valid control
2854 // packet, so we're done processing this packet now
2859 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2862 SV_ReadClientMessage();
2870 void NetConn_ServerFrame(void)
2873 lhnetaddress_t peeraddress;
2874 for (i = 0;i < sv_numsockets;i++)
2875 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2876 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2877 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2879 // never timeout loopback connections
2880 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2882 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2884 SV_DropClient(false);
2890 void NetConn_SleepMicroseconds(int microseconds)
2892 LHNET_SleepUntilPacket_Microseconds(microseconds);
2895 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2899 lhnetaddress_t masteraddress;
2900 lhnetaddress_t broadcastaddress;
2903 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2906 // 26000 is the default quake server port, servers on other ports will not
2908 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2909 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2913 for (i = 0;i < cl_numsockets;i++)
2917 const char *cmdname, *extraoptions;
2918 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2920 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2922 // search LAN for Quake servers
2923 SZ_Clear(&net_message);
2924 // save space for the header, filled in later
2925 MSG_WriteLong(&net_message, 0);
2926 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2927 MSG_WriteString(&net_message, "QUAKE");
2928 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2929 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2930 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2931 SZ_Clear(&net_message);
2933 // search LAN for DarkPlaces servers
2934 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2937 // build the getservers message to send to the dpmaster master servers
2938 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
2940 cmdname = "getserversExt";
2941 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
2945 cmdname = "getservers";
2948 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
2951 for (masternum = 0;sv_masters[masternum].name;masternum++)
2953 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2956 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2960 // search favorite servers
2961 for(j = 0; j < nFavorites; ++j)
2963 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2965 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2966 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
2973 // only query QuakeWorld servers when the user wants to
2976 for (i = 0;i < cl_numsockets;i++)
2980 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2982 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2984 // search LAN for QuakeWorld servers
2985 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2987 // build the getservers message to send to the qwmaster master servers
2988 // note this has no -1 prefix, and the trailing nul byte is sent
2989 dpsnprintf(request, sizeof(request), "c\n");
2993 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2995 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2997 if (m_state != m_slist)
2999 char lookupstring[128];
3000 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3001 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3004 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3008 // search favorite servers
3009 for(j = 0; j < nFavorites; ++j)
3011 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3013 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3015 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3016 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3023 if (!masterquerycount)
3025 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3026 M_Update_Return_Reason("No network");
3030 void NetConn_Heartbeat(int priority)
3032 lhnetaddress_t masteraddress;
3034 lhnetsocket_t *mysocket;
3036 // if it's a state change (client connected), limit next heartbeat to no
3037 // more than 30 sec in the future
3038 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3039 nextheartbeattime = realtime + 30.0;
3041 // limit heartbeatperiod to 30 to 270 second range,
3042 // lower limit is to avoid abusing master servers with excess traffic,
3043 // upper limit is to avoid timing out on the master server (which uses
3045 if (sv_heartbeatperiod.value < 30)
3046 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3047 if (sv_heartbeatperiod.value > 270)
3048 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3050 // make advertising optional and don't advertise singleplayer games, and
3051 // only send a heartbeat as often as the admin wants
3052 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3054 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3055 for (masternum = 0;sv_masters[masternum].name;masternum++)
3056 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3057 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3061 static void Net_Heartbeat_f(void)
3064 NetConn_Heartbeat(2);
3066 Con_Print("No server running, can not heartbeat to master server.\n");
3069 void PrintStats(netconn_t *conn)
3071 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3072 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3074 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3077 void Net_Stats_f(void)
3080 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3081 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3082 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3083 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3084 Con_Printf("packetsSent = %i\n", packetsSent);
3085 Con_Printf("packetsReSent = %i\n", packetsReSent);
3086 Con_Printf("packetsReceived = %i\n", packetsReceived);
3087 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3088 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3089 Con_Print("connections =\n");
3090 for (conn = netconn_list;conn;conn = conn->next)
3094 void Net_Refresh_f(void)
3096 if (m_state != m_slist) {
3097 Con_Print("Sending new requests to master servers\n");
3098 ServerList_QueryList(false, true, false, true);
3099 Con_Print("Listening for replies...\n");
3101 ServerList_QueryList(false, true, false, false);
3104 void Net_Slist_f(void)
3106 ServerList_ResetMasks();
3107 serverlist_sortbyfield = SLIF_PING;
3108 serverlist_sortflags = 0;
3109 if (m_state != m_slist) {
3110 Con_Print("Sending requests to master servers\n");
3111 ServerList_QueryList(true, true, false, true);
3112 Con_Print("Listening for replies...\n");
3114 ServerList_QueryList(true, true, false, false);
3117 void Net_SlistQW_f(void)
3119 ServerList_ResetMasks();
3120 serverlist_sortbyfield = SLIF_PING;
3121 serverlist_sortflags = 0;
3122 if (m_state != m_slist) {
3123 Con_Print("Sending requests to master servers\n");
3124 ServerList_QueryList(true, false, true, true);
3125 serverlist_consoleoutput = true;
3126 Con_Print("Listening for replies...\n");
3128 ServerList_QueryList(true, false, true, false);
3131 void NetConn_Init(void)
3134 lhnetaddress_t tempaddress;
3135 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3136 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3137 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3138 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3139 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3140 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3141 Cvar_RegisterVariable(&rcon_restricted_password);
3142 Cvar_RegisterVariable(&rcon_restricted_commands);
3143 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3144 Cvar_RegisterVariable(&net_slist_queriespersecond);
3145 Cvar_RegisterVariable(&net_slist_queriesperframe);
3146 Cvar_RegisterVariable(&net_slist_timeout);
3147 Cvar_RegisterVariable(&net_slist_maxtries);
3148 Cvar_RegisterVariable(&net_slist_favorites);
3149 Cvar_RegisterVariable(&net_slist_pause);
3150 Cvar_RegisterVariable(&net_messagetimeout);
3151 Cvar_RegisterVariable(&net_connecttimeout);
3152 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3153 Cvar_RegisterVariable(&cl_netlocalping);
3154 Cvar_RegisterVariable(&cl_netpacketloss_send);
3155 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3156 Cvar_RegisterVariable(&hostname);
3157 Cvar_RegisterVariable(&developer_networking);
3158 Cvar_RegisterVariable(&cl_netport);
3159 Cvar_RegisterVariable(&sv_netport);
3160 Cvar_RegisterVariable(&net_address);
3161 Cvar_RegisterVariable(&net_address_ipv6);
3162 Cvar_RegisterVariable(&sv_public);
3163 Cvar_RegisterVariable(&sv_heartbeatperiod);
3164 for (i = 0;sv_masters[i].name;i++)
3165 Cvar_RegisterVariable(&sv_masters[i]);
3166 Cvar_RegisterVariable(&gameversion);
3167 Cvar_RegisterVariable(&gameversion_min);
3168 Cvar_RegisterVariable(&gameversion_max);
3169 // 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.
3170 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3172 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3174 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3175 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3178 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3180 // 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
3181 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3183 i = atoi(com_argv[i + 1]);
3184 if (i >= 0 && i < 65536)
3186 Con_Printf("-port option used, setting port cvar to %i\n", i);
3187 Cvar_SetValueQuick(&sv_netport, i);
3190 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3194 net_message.data = net_message_buf;
3195 net_message.maxsize = sizeof(net_message_buf);
3196 net_message.cursize = 0;
3200 void NetConn_Shutdown(void)
3202 NetConn_CloseClientPorts();
3203 NetConn_CloseServerPorts();