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), when client and server gameversion mismatch in the server browser the server is shown as incompatible"};
85 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode"};
86 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
87 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)"};
88 extern cvar_t rcon_secure;
90 /* statistic counters */
91 static int packetsSent = 0;
92 static int packetsReSent = 0;
93 static int packetsReceived = 0;
94 static int receivedDuplicateCount = 0;
95 static int droppedDatagrams = 0;
97 static int unreliableMessagesSent = 0;
98 static int unreliableMessagesReceived = 0;
99 static int reliableMessagesSent = 0;
100 static int reliableMessagesReceived = 0;
102 double masterquerytime = -1000;
103 int masterquerycount = 0;
104 int masterreplycount = 0;
105 int serverquerycount = 0;
106 int serverreplycount = 0;
108 // this is only false if there are still servers left to query
109 static qboolean serverlist_querysleep = true;
110 static qboolean serverlist_paused = false;
111 // this is pushed a second or two ahead of realtime whenever a master server
112 // reply is received, to avoid issuing queries while master replies are still
113 // flooding in (which would make a mess of the ping times)
114 static double serverlist_querywaittime = 0;
116 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
117 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
119 static int cl_numsockets;
120 static lhnetsocket_t *cl_sockets[16];
121 static int sv_numsockets;
122 static lhnetsocket_t *sv_sockets[16];
124 netconn_t *netconn_list = NULL;
125 mempool_t *netconn_mempool = NULL;
127 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
128 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
129 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
130 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
132 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
133 int net_extresponse_count = 0;
134 int net_extresponse_last = 0;
136 // ServerList interface
137 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
138 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
140 serverlist_infofield_t serverlist_sortbyfield;
141 int serverlist_sortflags;
143 int serverlist_viewcount = 0;
144 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
146 int serverlist_cachecount;
147 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
149 qboolean serverlist_consoleoutput;
151 static int nFavorites = 0;
152 static lhnetaddress_t favorites[256];
154 void NetConn_UpdateFavorites()
158 p = net_slist_favorites.string;
159 while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
161 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
166 // helper function to insert a value into the viewset
167 // spare entries will be removed
168 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
171 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
172 i = serverlist_viewcount++;
174 i = SERVERLIST_VIEWLISTSIZE - 1;
177 for( ; i > index ; i-- )
178 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
180 serverlist_viewlist[index] = entry;
183 // we suppose serverlist_viewcount to be valid, ie > 0
184 static void _ServerList_ViewList_Helper_Remove( int index )
186 serverlist_viewcount--;
187 for( ; index < serverlist_viewcount ; index++ )
188 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
191 // returns true if A should be inserted before B
192 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
194 int result = 0; // > 0 if for numbers A > B and for text if A < B
196 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
198 if(A->info.isfavorite != B->info.isfavorite)
199 return A->info.isfavorite;
202 switch( serverlist_sortbyfield ) {
204 result = A->info.ping - B->info.ping;
206 case SLIF_MAXPLAYERS:
207 result = A->info.maxplayers - B->info.maxplayers;
209 case SLIF_NUMPLAYERS:
210 result = A->info.numplayers - B->info.numplayers;
213 result = A->info.numbots - B->info.numbots;
216 result = A->info.numhumans - B->info.numhumans;
219 result = A->info.freeslots - B->info.freeslots;
222 result = A->info.protocol - B->info.protocol;
225 result = strcmp( B->info.cname, A->info.cname );
228 result = strcasecmp( B->info.game, A->info.game );
231 result = strcasecmp( B->info.map, A->info.map );
234 result = strcasecmp( B->info.mod, A->info.mod );
237 result = strcasecmp( B->info.name, A->info.name );
240 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
242 case SLIF_ISFAVORITE:
243 result = !!B->info.isfavorite - !!A->info.isfavorite;
246 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
252 if( serverlist_sortflags & SLSF_DESCENDING )
258 // if the chosen sort key is identical, sort by index
259 // (makes this a stable sort, so that later replies from servers won't
260 // shuffle the servers around when they have the same ping)
264 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
266 // This should actually be done with some intermediate and end-of-function return
278 case SLMO_GREATEREQUAL:
280 case SLMO_NOTCONTAIN:
281 case SLMO_STARTSWITH:
282 case SLMO_NOTSTARTSWITH:
285 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
290 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
293 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
294 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
295 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
296 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
298 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
299 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
302 // Same here, also using an intermediate & final return would be more appropriate
306 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
307 case SLMO_NOTCONTAIN:
308 return !*bufferB || !strstr( bufferA, bufferB );
309 case SLMO_STARTSWITH:
310 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
311 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
312 case SLMO_NOTSTARTSWITH:
313 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
315 return strcmp( bufferA, bufferB ) < 0;
317 return strcmp( bufferA, bufferB ) <= 0;
319 return strcmp( bufferA, bufferB ) == 0;
321 return strcmp( bufferA, bufferB ) > 0;
323 return strcmp( bufferA, bufferB ) != 0;
324 case SLMO_GREATEREQUAL:
325 return strcmp( bufferA, bufferB ) >= 0;
327 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
332 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
334 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
336 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
338 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
340 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
342 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
344 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
346 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
348 if( *mask->info.cname
349 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
352 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
355 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
358 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
361 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
363 if( *mask->info.qcstatus
364 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
366 if( *mask->info.players
367 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
369 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
374 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
376 int start, end, mid, i;
379 // reject incompatible servers
380 if (entry->info.gameversion != gameversion.integer)
383 // refresh the "favorite" status
384 entry->info.isfavorite = false;
385 if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
387 for(i = 0; i < nFavorites; ++i)
389 if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
391 entry->info.isfavorite = true;
397 // FIXME: change this to be more readable (...)
398 // now check whether it passes through the masks
399 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
400 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
403 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
404 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
406 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
409 if( !serverlist_viewcount ) {
410 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
413 // ok, insert it, we just need to find out where exactly:
416 // check whether to insert it as new first item
417 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
418 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
420 } // check whether to insert it as new last item
421 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
422 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
426 end = serverlist_viewcount - 1;
427 while( end > start + 1 )
429 mid = (start + end) / 2;
430 // test the item that lies in the middle between start and end
431 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
432 // the item has to be in the upper half
435 // the item has to be in the lower half
438 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
441 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
444 for( i = 0; i < serverlist_viewcount; i++ )
446 if (serverlist_viewlist[i] == entry)
448 _ServerList_ViewList_Helper_Remove(i);
454 void ServerList_RebuildViewList(void)
458 serverlist_viewcount = 0;
459 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
460 serverlist_entry_t *entry = &serverlist_cache[i];
461 // also display entries that are currently being refreshed [11/8/2007 Black]
462 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
463 ServerList_ViewList_Insert( entry );
467 void ServerList_ResetMasks(void)
471 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
472 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
473 // numbots needs to be compared to -1 to always succeed
474 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
475 serverlist_andmasks[i].info.numbots = -1;
476 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
477 serverlist_ormasks[i].info.numbots = -1;
480 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
483 int numplayers = 0, maxplayers = 0;
484 for (i = 0;i < serverlist_cachecount;i++)
486 if (serverlist_cache[i].query == SQS_QUERIED)
488 numplayers += serverlist_cache[i].info.numhumans;
489 maxplayers += serverlist_cache[i].info.maxplayers;
492 *numplayerspointer = numplayers;
493 *maxplayerspointer = maxplayers;
497 static void _ServerList_Test(void)
500 for( i = 0 ; i < 1024 ; i++ ) {
501 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
502 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
503 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
504 serverlist_cache[serverlist_cachecount].finished = true;
505 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 );
506 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
507 serverlist_cachecount++;
512 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
514 masterquerytime = realtime;
515 masterquerycount = 0;
516 masterreplycount = 0;
518 serverquerycount = 0;
519 serverreplycount = 0;
520 serverlist_cachecount = 0;
521 serverlist_viewcount = 0;
523 // refresh all entries
525 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
526 serverlist_entry_t *entry = &serverlist_cache[ n ];
527 entry->query = SQS_REFRESHING;
528 entry->querycounter = 0;
531 serverlist_consoleoutput = consoleoutput;
533 //_ServerList_Test();
535 NetConn_QueryMasters(querydp, queryqw);
540 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
542 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
546 if (cl_netpacketloss_receive.integer)
547 for (i = 0;i < cl_numsockets;i++)
548 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
550 if (developer_networking.integer)
552 char addressstring[128], addressstring2[128];
553 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
556 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
557 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
558 Com_HexDumpToConsole((unsigned char *)data, length);
561 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
566 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
570 if (cl_netpacketloss_send.integer)
571 for (i = 0;i < cl_numsockets;i++)
572 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
574 ret = LHNET_Write(mysocket, data, length, peeraddress);
575 if (developer_networking.integer)
577 char addressstring[128], addressstring2[128];
578 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
579 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
580 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
581 Com_HexDumpToConsole((unsigned char *)data, length);
586 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
588 // note this does not include the trailing NULL because we add that in the parser
589 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
592 qboolean NetConn_CanSend(netconn_t *conn)
594 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
595 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
596 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
597 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
598 if (realtime > conn->cleartime)
602 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
607 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
611 // if this packet was supposedly choked, but we find ourselves sending one
612 // anyway, make sure the size counting starts at zero
613 // (this mostly happens on level changes and disconnects and such)
614 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
615 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
617 if (protocol == PROTOCOL_QUAKEWORLD)
620 qboolean sendreliable;
622 // note that it is ok to send empty messages to the qw server,
623 // otherwise it won't respond to us at all
625 sendreliable = false;
626 // if the remote side dropped the last reliable message, resend it
627 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
629 // if the reliable transmit buffer is empty, copy the current message out
630 if (!conn->sendMessageLength && conn->message.cursize)
632 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
633 conn->sendMessageLength = conn->message.cursize;
634 SZ_Clear(&conn->message); // clear the message buffer
635 conn->qw.reliable_sequence ^= 1;
638 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
639 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
640 // last received unreliable packet number, and last received reliable packet number (0 or 1)
641 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
643 conn->outgoing_unreliable_sequence++;
644 // client sends qport in every packet
645 if (conn == cls.netcon)
647 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
649 // also update cls.qw_outgoing_sequence
650 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
652 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
654 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
658 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
660 // add the reliable message if there is one
663 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
664 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
665 packetLen += conn->sendMessageLength;
666 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
669 // add the unreliable message if possible
670 if (packetLen + data->cursize <= 1400)
672 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
673 memcpy(sendbuffer + packetLen, data->data, data->cursize);
674 packetLen += data->cursize;
677 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
680 unreliableMessagesSent++;
682 totallen += packetLen + 28;
686 unsigned int packetLen;
687 unsigned int dataLen;
689 unsigned int *header;
691 // if a reliable message fragment has been lost, send it again
692 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
694 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
696 dataLen = conn->sendMessageLength;
701 dataLen = MAX_PACKETFRAGMENT;
705 packetLen = NET_HEADERSIZE + dataLen;
707 header = (unsigned int *)sendbuffer;
708 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
709 header[1] = BigLong(conn->nq.sendSequence - 1);
710 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
712 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
714 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
716 conn->lastSendTime = realtime;
720 totallen += packetLen + 28;
723 // if we have a new reliable message to send, do so
724 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
726 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
728 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
729 conn->message.overflowed = true;
733 if (developer_networking.integer && conn == cls.netcon)
735 Con_Print("client sending reliable message to server:\n");
736 SZ_HexDumpToConsole(&conn->message);
739 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
740 conn->sendMessageLength = conn->message.cursize;
741 SZ_Clear(&conn->message);
743 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
745 dataLen = conn->sendMessageLength;
750 dataLen = MAX_PACKETFRAGMENT;
754 packetLen = NET_HEADERSIZE + dataLen;
756 header = (unsigned int *)sendbuffer;
757 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
758 header[1] = BigLong(conn->nq.sendSequence);
759 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
761 conn->nq.sendSequence++;
763 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
765 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
767 conn->lastSendTime = realtime;
769 reliableMessagesSent++;
771 totallen += packetLen + 28;
774 // if we have an unreliable message to send, do so
777 packetLen = NET_HEADERSIZE + data->cursize;
779 if (packetLen > (int)sizeof(sendbuffer))
781 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
785 header = (unsigned int *)sendbuffer;
786 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
787 header[1] = BigLong(conn->outgoing_unreliable_sequence);
788 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
790 conn->outgoing_unreliable_sequence++;
792 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
794 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
797 unreliableMessagesSent++;
799 totallen += packetLen + 28;
803 // delay later packets to obey rate limit
804 if (conn->cleartime < realtime - 0.1)
805 conn->cleartime = realtime - 0.1;
806 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
807 if (conn->cleartime < realtime)
808 conn->cleartime = realtime;
813 qboolean NetConn_HaveClientPorts(void)
815 return !!cl_numsockets;
818 qboolean NetConn_HaveServerPorts(void)
820 return !!sv_numsockets;
823 void NetConn_CloseClientPorts(void)
825 for (;cl_numsockets > 0;cl_numsockets--)
826 if (cl_sockets[cl_numsockets - 1])
827 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
830 void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
832 lhnetaddress_t address;
835 char addressstring2[1024];
836 if (addressstring && addressstring[0])
837 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
839 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
842 if ((s = LHNET_OpenSocket_Connectionless(&address)))
844 cl_sockets[cl_numsockets++] = s;
845 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
846 Con_Printf("Client opened a socket on address %s\n", addressstring2);
850 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
851 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
855 Con_Printf("Client unable to parse address %s\n", addressstring);
858 void NetConn_OpenClientPorts(void)
861 NetConn_CloseClientPorts();
862 port = bound(0, cl_netport.integer, 65535);
863 if (cl_netport.integer != port)
864 Cvar_SetValueQuick(&cl_netport, port);
866 Con_Printf("Client using an automatically assigned port\n");
868 Con_Printf("Client using port %i\n", port);
869 NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
870 NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
871 NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
874 void NetConn_CloseServerPorts(void)
876 for (;sv_numsockets > 0;sv_numsockets--)
877 if (sv_sockets[sv_numsockets - 1])
878 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
881 qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
883 lhnetaddress_t address;
886 char addressstring2[1024];
889 for (port = defaultport; port <= defaultport + range; port++)
891 if (addressstring && addressstring[0])
892 success = LHNETADDRESS_FromString(&address, addressstring, port);
894 success = LHNETADDRESS_FromPort(&address, addresstype, port);
897 if ((s = LHNET_OpenSocket_Connectionless(&address)))
899 sv_sockets[sv_numsockets++] = s;
900 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
901 Con_Printf("Server listening on address %s\n", addressstring2);
906 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
907 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
912 Con_Printf("Server unable to parse address %s\n", addressstring);
913 // if it cant parse one address, it wont be able to parse another for sure
920 void NetConn_OpenServerPorts(int opennetports)
923 NetConn_CloseServerPorts();
924 NetConn_UpdateSockets();
925 port = bound(0, sv_netport.integer, 65535);
928 Con_Printf("Server using port %i\n", port);
929 if (sv_netport.integer != port)
930 Cvar_SetValueQuick(&sv_netport, port);
931 if (cls.state != ca_dedicated)
932 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
935 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
936 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
938 if (sv_numsockets == 0)
939 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
942 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
944 int i, a = LHNETADDRESS_GetAddressType(address);
945 for (i = 0;i < cl_numsockets;i++)
946 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
947 return cl_sockets[i];
951 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
953 int i, a = LHNETADDRESS_GetAddressType(address);
954 for (i = 0;i < sv_numsockets;i++)
955 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
956 return sv_sockets[i];
960 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
963 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
964 conn->mysocket = mysocket;
965 conn->peeraddress = *peeraddress;
966 conn->lastMessageTime = realtime;
967 conn->message.data = conn->messagedata;
968 conn->message.maxsize = sizeof(conn->messagedata);
969 conn->message.cursize = 0;
970 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
971 // reduce effectiveness of connection request floods
972 conn->timeout = realtime + net_connecttimeout.value;
973 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
974 conn->next = netconn_list;
979 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
980 void NetConn_Close(netconn_t *conn)
983 // remove connection from list
985 // allow the client to reconnect immediately
986 NetConn_ClearConnectFlood(&(conn->peeraddress));
988 if (conn == netconn_list)
989 netconn_list = conn->next;
992 for (c = netconn_list;c;c = c->next)
996 c->next = conn->next;
1000 // not found in list, we'll avoid crashing here...
1008 static int clientport = -1;
1009 static int clientport2 = -1;
1010 static int hostport = -1;
1011 void NetConn_UpdateSockets(void)
1013 if (cls.state != ca_dedicated)
1015 if (clientport2 != cl_netport.integer)
1017 clientport2 = cl_netport.integer;
1018 if (cls.state == ca_connected)
1019 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1021 if (cls.state == ca_disconnected && clientport != clientport2)
1023 clientport = clientport2;
1024 NetConn_CloseClientPorts();
1026 if (cl_numsockets == 0)
1027 NetConn_OpenClientPorts();
1030 if (hostport != sv_netport.integer)
1032 hostport = sv_netport.integer;
1034 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1038 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1040 int originallength = length;
1044 if (protocol == PROTOCOL_QUAKEWORLD)
1046 int sequence, sequence_ack;
1047 int reliable_ack, reliable_message;
1051 sequence = LittleLong(*((int *)(data + 0)));
1052 sequence_ack = LittleLong(*((int *)(data + 4)));
1056 if (conn != cls.netcon)
1061 // 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?)
1062 qport = LittleShort(*((int *)(data + 8)));
1068 reliable_message = (sequence >> 31) & 1;
1069 reliable_ack = (sequence_ack >> 31) & 1;
1070 sequence &= ~(1<<31);
1071 sequence_ack &= ~(1<<31);
1072 if (sequence <= conn->qw.incoming_sequence)
1074 //Con_DPrint("Got a stale datagram\n");
1077 count = sequence - (conn->qw.incoming_sequence + 1);
1080 droppedDatagrams += count;
1081 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1084 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1085 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1086 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1087 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1090 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1091 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1092 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1093 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1094 if (reliable_ack == conn->qw.reliable_sequence)
1096 // received, now we will be able to send another reliable message
1097 conn->sendMessageLength = 0;
1098 reliableMessagesReceived++;
1100 conn->qw.incoming_sequence = sequence;
1101 if (conn == cls.netcon)
1102 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1103 conn->qw.incoming_acknowledged = sequence_ack;
1104 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1105 if (reliable_message)
1106 conn->qw.incoming_reliable_sequence ^= 1;
1107 conn->lastMessageTime = realtime;
1108 conn->timeout = realtime + newtimeout;
1109 unreliableMessagesReceived++;
1110 SZ_Clear(&net_message);
1111 SZ_Write(&net_message, data, length);
1119 unsigned int sequence;
1122 qlength = (unsigned int)BigLong(((int *)data)[0]);
1123 flags = qlength & ~NETFLAG_LENGTH_MASK;
1124 qlength &= NETFLAG_LENGTH_MASK;
1125 // control packets were already handled
1126 if (!(flags & NETFLAG_CTL) && qlength == length)
1128 sequence = BigLong(((int *)data)[1]);
1132 if (flags & NETFLAG_UNRELIABLE)
1134 if (sequence >= conn->nq.unreliableReceiveSequence)
1136 if (sequence > conn->nq.unreliableReceiveSequence)
1138 count = sequence - conn->nq.unreliableReceiveSequence;
1139 droppedDatagrams += count;
1140 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1143 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1144 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1145 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1146 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1149 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1150 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1151 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1152 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1153 conn->nq.unreliableReceiveSequence = sequence + 1;
1154 conn->lastMessageTime = realtime;
1155 conn->timeout = realtime + newtimeout;
1156 unreliableMessagesReceived++;
1159 SZ_Clear(&net_message);
1160 SZ_Write(&net_message, data, length);
1166 // Con_DPrint("Got a stale datagram\n");
1169 else if (flags & NETFLAG_ACK)
1171 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1172 if (sequence == (conn->nq.sendSequence - 1))
1174 if (sequence == conn->nq.ackSequence)
1176 conn->nq.ackSequence++;
1177 if (conn->nq.ackSequence != conn->nq.sendSequence)
1178 Con_DPrint("ack sequencing error\n");
1179 conn->lastMessageTime = realtime;
1180 conn->timeout = realtime + newtimeout;
1181 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1183 unsigned int packetLen;
1184 unsigned int dataLen;
1186 unsigned int *header;
1188 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1189 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1191 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1193 dataLen = conn->sendMessageLength;
1198 dataLen = MAX_PACKETFRAGMENT;
1202 packetLen = NET_HEADERSIZE + dataLen;
1204 header = (unsigned int *)sendbuffer;
1205 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1206 header[1] = BigLong(conn->nq.sendSequence);
1207 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1209 conn->nq.sendSequence++;
1211 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1213 conn->lastSendTime = realtime;
1218 conn->sendMessageLength = 0;
1221 // Con_DPrint("Duplicate ACK received\n");
1224 // Con_DPrint("Stale ACK received\n");
1227 else if (flags & NETFLAG_DATA)
1229 unsigned int temppacket[2];
1230 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1231 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1232 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1233 temppacket[1] = BigLong(sequence);
1234 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1235 if (sequence == conn->nq.receiveSequence)
1237 conn->lastMessageTime = realtime;
1238 conn->timeout = realtime + newtimeout;
1239 conn->nq.receiveSequence++;
1240 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1241 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1242 conn->receiveMessageLength += length;
1244 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1245 "Dropping the message!\n", sequence );
1246 conn->receiveMessageLength = 0;
1249 if (flags & NETFLAG_EOM)
1251 reliableMessagesReceived++;
1252 length = conn->receiveMessageLength;
1253 conn->receiveMessageLength = 0;
1256 SZ_Clear(&net_message);
1257 SZ_Write(&net_message, conn->receiveMessage, length);
1264 receivedDuplicateCount++;
1272 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1274 cls.connect_trying = false;
1275 M_Update_Return_Reason("");
1276 // the connection request succeeded, stop current connection and set up a new connection
1278 // if we're connecting to a remote server, shut down any local server
1279 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1280 Host_ShutdownServer ();
1281 // allocate a net connection to keep track of things
1282 cls.netcon = NetConn_Open(mysocket, peeraddress);
1283 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1284 key_dest = key_game;
1286 cls.demonum = -1; // not in the demo loop now
1287 cls.state = ca_connected;
1288 cls.signon = 0; // need all the signon messages before playing
1289 cls.protocol = initialprotocol;
1290 // reset move sequence numbering on this new connection
1291 cls.servermovesequence = 0;
1292 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1293 Cmd_ForwardStringToServer("new");
1294 if (cls.protocol == PROTOCOL_QUAKE)
1296 // write a keepalive (clc_nop) as it seems to greatly improve the
1297 // chances of connecting to a netquake server
1299 unsigned char buf[4];
1300 memset(&msg, 0, sizeof(msg));
1302 msg.maxsize = sizeof(buf);
1303 MSG_WriteChar(&msg, clc_nop);
1304 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1308 int NetConn_IsLocalGame(void)
1310 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1315 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1319 serverlist_entry_t *entry = NULL;
1321 // search the cache for this server and update it
1322 for (n = 0;n < serverlist_cachecount;n++) {
1323 entry = &serverlist_cache[ n ];
1324 if (!strcmp(addressstring, entry->info.cname))
1328 if (n == serverlist_cachecount)
1330 // LAN search doesnt require an answer from the master server so we wont
1331 // know the ping nor will it be initialized already...
1334 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1337 entry = &serverlist_cache[n];
1339 memset(entry, 0, sizeof(*entry));
1340 // store the data the engine cares about (address and ping)
1341 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1342 entry->info.ping = 100000;
1343 entry->querytime = realtime;
1344 // if not in the slist menu we should print the server to console
1345 if (serverlist_consoleoutput)
1346 Con_Printf("querying %s\n", addressstring);
1347 ++serverlist_cachecount;
1349 // if this is the first reply from this server, count it as having replied
1350 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1351 pingtime = bound(0, pingtime, 9999);
1352 if (entry->query == SQS_REFRESHING) {
1353 entry->info.ping = pingtime;
1354 entry->query = SQS_QUERIED;
1356 // convert to unsigned to catch the -1
1357 // 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]
1358 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1362 // other server info is updated by the caller
1366 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1368 serverlist_entry_t *entry = &serverlist_cache[n];
1369 serverlist_info_t *info = &entry->info;
1370 // update description strings for engine menu and console output
1371 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);
1372 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
1373 if (entry->query == SQS_QUERIED)
1375 if(!serverlist_paused)
1376 ServerList_ViewList_Remove(entry);
1378 // if not in the slist menu we should print the server to console (if wanted)
1379 else if( serverlist_consoleoutput )
1380 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1381 // and finally, update the view set
1382 if(!serverlist_paused)
1383 ServerList_ViewList_Insert( entry );
1384 // update the entry's state
1385 serverlist_cache[n].query = SQS_QUERIED;
1388 // returns true, if it's sensible to continue the processing
1389 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1391 serverlist_entry_t *entry;
1393 // ignore the rest of the message if the serverlist is full
1394 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1396 // also ignore it if we have already queried it (other master server response)
1397 for( n = 0 ; n < serverlist_cachecount ; n++ )
1398 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1401 entry = &serverlist_cache[n];
1403 if( n < serverlist_cachecount ) {
1404 // the entry has already been queried once or
1408 memset(entry, 0, sizeof(entry));
1409 entry->protocol = protocol;
1410 // store the data the engine cares about (address and ping)
1411 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1413 entry->info.isfavorite = isfavorite;
1415 // no, then reset the ping right away
1416 entry->info.ping = -1;
1417 // we also want to increase the serverlist_cachecount then
1418 serverlist_cachecount++;
1421 entry->query = SQS_QUERYING;
1426 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1429 if (serverlist_consoleoutput)
1430 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1433 char ipstring [128];
1436 if (data[0] == '\\')
1438 unsigned short port = data[5] * 256 + data[6];
1440 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1441 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1443 // move on to next address in packet
1448 else if (data[0] == '/' && isextended && length >= 19)
1450 unsigned short port = data[17] * 256 + data[18];
1456 // TODO: make some basic checks of the IP address (broadcast, ...)
1458 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1461 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1462 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1463 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1468 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1469 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1470 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1475 // move on to next address in packet
1481 Con_Print("Error while parsing the server list\n");
1485 if (serverlist_consoleoutput && developer_networking.integer)
1486 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1488 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1494 // begin or resume serverlist queries
1495 serverlist_querysleep = false;
1496 serverlist_querywaittime = realtime + 3;
1499 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1501 qboolean fromserver;
1502 int ret, c, control;
1504 char *string, addressstring2[128], ipstring[32];
1505 char stringbuf[16384];
1507 // quakeworld ingame packet
1508 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1510 // convert the address to a string incase we need it
1511 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1513 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1515 // received a command string - strip off the packaging and put it
1516 // into our string buffer with NULL termination
1519 length = min(length, (int)sizeof(stringbuf) - 1);
1520 memcpy(stringbuf, data, length);
1521 stringbuf[length] = 0;
1524 if (developer_networking.integer)
1526 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1527 Com_HexDumpToConsole(data, length);
1530 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1532 // darkplaces or quake3
1533 char protocolnames[1400];
1534 Protocol_Names(protocolnames, sizeof(protocolnames));
1535 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1536 M_Update_Return_Reason("Got challenge response");
1537 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1538 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1539 // TODO: add userinfo stuff here instead of using NQ commands?
1540 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1543 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1545 // darkplaces or quake3
1546 M_Update_Return_Reason("Accepted");
1547 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1550 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1552 char rejectreason[32];
1553 cls.connect_trying = false;
1555 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1556 memcpy(rejectreason, string, length);
1557 rejectreason[length] = 0;
1558 M_Update_Return_Reason(rejectreason);
1561 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1563 serverlist_info_t *info;
1568 // search the cache for this server and update it
1569 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1573 info = &serverlist_cache[n].info;
1578 info->qcstatus[0] = 0;
1579 info->players[0] = 0;
1580 info->protocol = -1;
1581 info->numplayers = 0;
1583 info->maxplayers = 0;
1584 info->gameversion = 0;
1586 p = strchr(string, '\n');
1589 *p = 0; // cut off the string there
1593 Con_Printf("statusResponse without players block?\n");
1595 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1596 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1597 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1598 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1599 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1600 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1601 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1602 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1603 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1604 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1605 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1606 info->numhumans = info->numplayers - max(0, info->numbots);
1607 info->freeslots = info->maxplayers - info->numplayers;
1609 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1613 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1615 serverlist_info_t *info;
1619 // search the cache for this server and update it
1620 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1624 info = &serverlist_cache[n].info;
1629 info->qcstatus[0] = 0;
1630 info->players[0] = 0;
1631 info->protocol = -1;
1632 info->numplayers = 0;
1634 info->maxplayers = 0;
1635 info->gameversion = 0;
1637 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1638 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1639 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1640 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1641 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1642 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1643 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1644 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1645 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1646 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1647 info->numhumans = info->numplayers - max(0, info->numbots);
1648 info->freeslots = info->maxplayers - info->numplayers;
1650 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1654 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1656 // Extract the IP addresses
1659 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1662 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1664 // Extract the IP addresses
1667 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1670 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1672 // Extract the IP addresses
1676 if (serverlist_consoleoutput)
1677 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1678 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1680 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1681 if (serverlist_consoleoutput && developer_networking.integer)
1682 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1684 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1688 // move on to next address in packet
1692 // begin or resume serverlist queries
1693 serverlist_querysleep = false;
1694 serverlist_querywaittime = realtime + 3;
1697 if (!strncmp(string, "extResponse ", 12))
1699 ++net_extresponse_count;
1700 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1701 net_extresponse_count = NET_EXTRESPONSE_MAX;
1702 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1703 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1706 if (!strncmp(string, "ping", 4))
1708 if (developer.integer >= 10)
1709 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1710 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1713 if (!strncmp(string, "ack", 3))
1715 // QuakeWorld compatibility
1716 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1718 // challenge message
1719 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1720 M_Update_Return_Reason("Got QuakeWorld challenge response");
1721 cls.qw_qport = qport.integer;
1722 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1723 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1724 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1727 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1730 M_Update_Return_Reason("QuakeWorld Accepted");
1731 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1734 if (length > 2 && !memcmp(string, "n\\", 2))
1736 serverlist_info_t *info;
1740 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1741 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1744 // search the cache for this server and update it
1745 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1749 info = &serverlist_cache[n].info;
1750 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1751 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1752 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1753 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1755 info->numplayers = 0; // updated below
1756 info->numhumans = 0; // updated below
1757 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1758 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1760 // count active players on server
1761 // (we could gather more info, but we're just after the number)
1762 s = strchr(string, '\n');
1766 while (s < string + length)
1768 for (;s < string + length && *s != '\n';s++)
1770 if (s >= string + length)
1778 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1782 if (string[0] == 'n')
1785 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1787 // we may not have liked the packet, but it was a command packet, so
1788 // we're done processing this packet now
1791 // quakeworld ingame packet
1792 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1795 CL_ParseServerMessage();
1798 // netquake control packets, supported for compatibility only
1799 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1802 serverlist_info_t *info;
1806 SZ_Clear(&net_message);
1807 SZ_Write(&net_message, data, length);
1813 if (developer.integer >= 10)
1814 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1815 if (cls.connect_trying)
1817 lhnetaddress_t clientportaddress;
1818 clientportaddress = *peeraddress;
1819 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1820 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1821 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1822 M_Update_Return_Reason("Accepted");
1823 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1827 if (developer.integer >= 10)
1828 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1829 cls.connect_trying = false;
1830 M_Update_Return_Reason((char *)MSG_ReadString());
1832 case CCREP_SERVER_INFO:
1833 if (developer.integer >= 10)
1834 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1835 // LordHavoc: because the quake server may report weird addresses
1836 // we just ignore it and keep the real address
1838 // search the cache for this server and update it
1839 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1843 info = &serverlist_cache[n].info;
1844 strlcpy(info->game, "Quake", sizeof(info->game));
1845 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1846 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1847 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1848 info->numplayers = MSG_ReadByte();
1849 info->maxplayers = MSG_ReadByte();
1850 info->protocol = MSG_ReadByte();
1852 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1855 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1856 if (developer.integer >= 10)
1857 Con_Printf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1859 Con_Printf("%s\n", MSG_ReadString());
1861 case CCREP_PLAYER_INFO:
1862 // we got a CCREP_PLAYER_INFO??
1863 //if (developer.integer >= 10)
1864 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1866 case CCREP_RULE_INFO:
1867 // we got a CCREP_RULE_INFO??
1868 //if (developer.integer >= 10)
1869 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1874 SZ_Clear(&net_message);
1875 // we may not have liked the packet, but it was a valid control
1876 // packet, so we're done processing this packet now
1880 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1881 CL_ParseServerMessage();
1885 void NetConn_QueryQueueFrame(void)
1891 static double querycounter = 0;
1893 if(!net_slist_pause.integer && serverlist_paused)
1894 ServerList_RebuildViewList();
1895 serverlist_paused = net_slist_pause.integer;
1897 if (serverlist_querysleep)
1900 // apply a cool down time after master server replies,
1901 // to avoid messing up the ping times on the servers
1902 if (serverlist_querywaittime > realtime)
1905 // each time querycounter reaches 1.0 issue a query
1906 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1907 maxqueries = (int)querycounter;
1908 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1909 querycounter -= maxqueries;
1911 if( maxqueries == 0 ) {
1915 // scan serverlist and issue queries as needed
1916 serverlist_querysleep = true;
1918 timeouttime = realtime - net_slist_timeout.value;
1919 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1921 serverlist_entry_t *entry = &serverlist_cache[ index ];
1922 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1927 serverlist_querysleep = false;
1928 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1933 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1935 lhnetaddress_t address;
1938 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1939 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1941 for (socket = 0; socket < cl_numsockets ; socket++)
1942 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1946 for (socket = 0; socket < cl_numsockets ; socket++)
1947 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1950 // update the entry fields
1951 entry->querytime = realtime;
1952 entry->querycounter++;
1954 // if not in the slist menu we should print the server to console
1955 if (serverlist_consoleoutput)
1956 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1962 // have we tried to refresh this server?
1963 if( entry->query == SQS_REFRESHING ) {
1964 // yes, so update the reply count (since its not responding anymore)
1966 if(!serverlist_paused)
1967 ServerList_ViewList_Remove(entry);
1969 entry->query = SQS_TIMEDOUT;
1974 void NetConn_ClientFrame(void)
1977 lhnetaddress_t peeraddress;
1978 NetConn_UpdateSockets();
1979 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1981 if (cls.connect_remainingtries == 0)
1982 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1983 cls.connect_nextsendtime = realtime + 1;
1984 cls.connect_remainingtries--;
1985 if (cls.connect_remainingtries <= -10)
1987 cls.connect_trying = false;
1988 M_Update_Return_Reason("Connect: Failed");
1991 // try challenge first (newer DP server or QW)
1992 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1993 // then try netquake as a fallback (old server, or netquake)
1994 SZ_Clear(&net_message);
1995 // save space for the header, filled in later
1996 MSG_WriteLong(&net_message, 0);
1997 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1998 MSG_WriteString(&net_message, "QUAKE");
1999 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2000 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2001 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2002 SZ_Clear(&net_message);
2004 for (i = 0;i < cl_numsockets;i++)
2005 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2006 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2007 NetConn_QueryQueueFrame();
2008 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2010 Con_Print("Connection timed out\n");
2012 Host_ShutdownServer ();
2016 #define MAX_CHALLENGES 128
2019 lhnetaddress_t address;
2023 challenge[MAX_CHALLENGES];
2025 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2029 for (i = 0;i < bufferlength - 1;i++)
2033 c = rand () % (127 - 33) + 33;
2034 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2040 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2041 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2044 unsigned int nb_clients = 0, nb_bots = 0, i;
2050 // How many clients are there?
2051 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2053 if (svs.clients[i].active)
2056 if (!svs.clients[i].netconnection)
2062 if(prog->globaloffsets.worldstatus >= 0)
2064 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2070 for(q = str; *q; ++q)
2071 if(*q != '\\' && *q != '\n')
2077 // TODO: we should add more information for the full status string
2078 length = dpsnprintf(out_msg, out_size,
2079 "\377\377\377\377%s\x0A"
2080 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2081 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2085 fullstatus ? "statusResponse" : "infoResponse",
2086 gamename, com_modname, gameversion.integer, svs.maxclients,
2087 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2088 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2089 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2090 fullstatus ? "\n" : "");
2092 // Make sure it fits in the buffer
2102 savelength = length;
2104 ptr = out_msg + length;
2105 left = (int)out_size - length;
2107 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2109 client_t *cl = &svs.clients[i];
2112 int nameind, cleanind, pingvalue;
2114 char cleanname [sizeof(cl->name)];
2116 // Remove all characters '"' and '\' in the player name
2121 curchar = cl->name[nameind++];
2122 if (curchar != '"' && curchar != '\\')
2124 cleanname[cleanind++] = curchar;
2125 if (cleanind == sizeof(cleanname) - 1)
2128 } while (curchar != '\0');
2129 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2131 pingvalue = (int)(cl->ping * 1000.0f);
2132 if(cl->netconnection)
2133 pingvalue = bound(1, pingvalue, 9999);
2138 if(prog->fieldoffsets.clientstatus >= 0)
2140 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2146 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2147 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2153 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2155 if(cl->frags == -666) // spectator
2156 strlcpy(teambuf, " 0", sizeof(teambuf));
2157 else if(cl->colors == 0x44) // red team
2158 strlcpy(teambuf, " 1", sizeof(teambuf));
2159 else if(cl->colors == 0xDD) // blue team
2160 strlcpy(teambuf, " 2", sizeof(teambuf));
2161 else if(cl->colors == 0xCC) // yellow team
2162 strlcpy(teambuf, " 3", sizeof(teambuf));
2163 else if(cl->colors == 0x99) // pink team
2164 strlcpy(teambuf, " 4", sizeof(teambuf));
2166 strlcpy(teambuf, " 0", sizeof(teambuf));
2171 // note: team number is inserted according to SoF2 protocol
2173 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2179 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2188 // turn it into an infoResponse!
2189 out_msg[savelength] = 0;
2190 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2191 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2208 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2210 int floodslotnum, bestfloodslotnum;
2211 double bestfloodtime;
2212 lhnetaddress_t noportpeeraddress;
2213 // see if this is a connect flood
2214 noportpeeraddress = *peeraddress;
2215 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2216 bestfloodslotnum = 0;
2217 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2218 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2220 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2222 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2223 bestfloodslotnum = floodslotnum;
2225 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2227 // this address matches an ongoing flood address
2228 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2230 // renew the ban on this address so it does not expire
2231 // until the flood has subsided
2232 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2233 //Con_Printf("Flood detected!\n");
2236 // the flood appears to have subsided, so allow this
2237 bestfloodslotnum = floodslotnum; // reuse the same slot
2241 // begin a new timeout on this address
2242 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2243 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2244 //Con_Printf("Flood detection initiated!\n");
2248 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2251 lhnetaddress_t noportpeeraddress;
2252 // see if this is a connect flood
2253 noportpeeraddress = *peeraddress;
2254 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2255 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2257 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2259 // this address matches an ongoing flood address
2261 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2262 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2263 //Con_Printf("Flood cleared!\n");
2268 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2270 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2275 t1 = (long) time(NULL);
2276 t2 = strtol(s, NULL, 0);
2277 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2280 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2283 return !memcmp(mdfourbuf, hash, 16);
2286 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2288 return !strcmp(password, hash);
2291 // returns a string describing the user level, or NULL for auth failure
2292 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2297 if(comparator(rcon_password.string, password, cs, cslen))
2300 if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2303 for(text = s; text != endpos; ++text)
2304 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2305 return NULL; // block possible exploits against the parser/alias expansion
2309 size_t l = strlen(s);
2312 hasquotes = (strchr(s, '"') != NULL);
2313 // sorry, we can't allow these substrings in wildcard expressions,
2314 // as they can mess with the argument counts
2315 text = rcon_restricted_commands.string;
2316 while(COM_ParseToken_Console(&text))
2318 // com_token now contains a pattern to check for...
2319 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2322 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2325 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2327 if(!strcmp(com_token, s))
2330 else // single-arg expression? must match the beginning of the command
2332 if(!strcmp(com_token, s))
2334 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2338 // if we got here, nothing matched!
2345 return "restricted rcon";
2348 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2352 // looks like a legitimate rcon command with the correct password
2353 const char *s_ptr = s;
2354 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2355 while(s_ptr != endpos)
2357 size_t l = strlen(s_ptr);
2359 Con_Printf(" %s;", s_ptr);
2364 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2365 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2368 size_t l = strlen(s);
2371 client_t *host_client_save = host_client;
2372 Cmd_ExecuteString(s, src_command);
2373 host_client = host_client_save;
2374 // in case it is a command that changes host_client (like restart)
2378 Con_Rcon_Redirect_End();
2382 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2386 extern void SV_SendServerinfo (client_t *client);
2387 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2389 int i, ret, clientnum, best;
2392 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2393 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2398 // convert the address to a string incase we need it
2399 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2401 // see if we can identify the sender as a local player
2402 // (this is necessary for rcon to send a reliable reply if the client is
2403 // actually on the server, not sending remotely)
2404 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2405 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2407 if (i == svs.maxclients)
2410 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2412 // received a command string - strip off the packaging and put it
2413 // into our string buffer with NULL termination
2416 length = min(length, (int)sizeof(stringbuf) - 1);
2417 memcpy(stringbuf, data, length);
2418 stringbuf[length] = 0;
2421 if (developer.integer >= 10)
2423 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2424 Com_HexDumpToConsole(data, length);
2427 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2429 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2431 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2433 if (besttime > challenge[i].time)
2434 besttime = challenge[best = i].time;
2436 // if we did not find an exact match, choose the oldest and
2437 // update address and string
2438 if (i == MAX_CHALLENGES)
2441 challenge[i].address = *peeraddress;
2442 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2444 challenge[i].time = realtime;
2445 // send the challenge
2446 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2449 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2454 if (!(s = SearchInfostring(string, "challenge")))
2456 // validate the challenge
2457 for (i = 0;i < MAX_CHALLENGES;i++)
2458 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2460 // if the challenge is not recognized, drop the packet
2461 if (i == MAX_CHALLENGES)
2464 // check engine protocol
2465 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2467 if (developer.integer >= 10)
2468 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2469 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2473 // see if this is a duplicate connection request or a disconnected
2474 // client who is rejoining to the same client slot
2475 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2477 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2479 // this is a known client...
2480 if (client->spawned)
2482 // client crashed and is coming back,
2483 // keep their stuff intact
2484 if (developer.integer >= 10)
2485 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2486 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2488 SV_SendServerinfo(client);
2493 // client is still trying to connect,
2494 // so we send a duplicate reply
2495 if (developer.integer >= 10)
2496 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2497 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2503 if (NetConn_PreventConnectFlood(peeraddress))
2506 // find an empty client slot for this new client
2507 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2510 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2512 // allocated connection
2513 if (developer.integer >= 10)
2514 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2515 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2516 // now set up the client
2518 SV_ConnectClient(clientnum, conn);
2520 NetConn_Heartbeat(1);
2525 // no empty slots found - server is full
2526 if (developer.integer >= 10)
2527 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2528 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2532 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2534 const char *challenge = NULL;
2536 // If there was a challenge in the getinfo message
2537 if (length > 8 && string[7] == ' ')
2538 challenge = string + 8;
2540 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2542 if (developer.integer >= 10)
2543 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2544 NetConn_WriteString(mysocket, response, peeraddress);
2548 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2550 const char *challenge = NULL;
2552 // If there was a challenge in the getinfo message
2553 if (length > 10 && string[9] == ' ')
2554 challenge = string + 10;
2556 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2558 if (developer.integer >= 10)
2559 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2560 NetConn_WriteString(mysocket, response, peeraddress);
2564 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2566 char *password = string + 20;
2567 char *timeval = string + 37;
2568 char *s = strchr(timeval, ' ');
2569 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2570 const char *userlevel;
2572 return true; // invalid packet
2575 userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2576 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2579 if (length >= 5 && !memcmp(string, "rcon ", 5))
2582 char *s = string + 5;
2583 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2586 if(rcon_secure.integer)
2589 for (i = 0;!ISWHITESPACE(*s);s++)
2590 if (i < (int)sizeof(password) - 1)
2592 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2595 if (!ISWHITESPACE(password[0]))
2597 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2598 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2602 if (!strncmp(string, "ping", 4))
2604 if (developer.integer >= 10)
2605 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2606 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2609 if (!strncmp(string, "ack", 3))
2611 // we may not have liked the packet, but it was a command packet, so
2612 // we're done processing this packet now
2615 // netquake control packets, supported for compatibility only, and only
2616 // when running game protocols that are normally served via this connection
2618 // (this protects more modern protocols against being used for
2619 // Quake packet flood Denial Of Service attacks)
2620 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))
2624 const char *protocolname;
2627 SZ_Clear(&net_message);
2628 SZ_Write(&net_message, data, length);
2634 if (developer.integer >= 10)
2635 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2636 if(!islocal && sv_public.integer <= -2)
2639 protocolname = MSG_ReadString();
2640 protocolnumber = MSG_ReadByte();
2641 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2643 if (developer.integer >= 10)
2644 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2645 SZ_Clear(&net_message);
2646 // save space for the header, filled in later
2647 MSG_WriteLong(&net_message, 0);
2648 MSG_WriteByte(&net_message, CCREP_REJECT);
2649 MSG_WriteString(&net_message, "Incompatible version.\n");
2650 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2651 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2652 SZ_Clear(&net_message);
2656 // see if this connect request comes from a known client
2657 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2659 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2661 // this is either a duplicate connection request
2662 // or coming back from a timeout
2663 // (if so, keep their stuff intact)
2666 if (developer.integer >= 10)
2667 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2668 SZ_Clear(&net_message);
2669 // save space for the header, filled in later
2670 MSG_WriteLong(&net_message, 0);
2671 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2672 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2673 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2674 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2675 SZ_Clear(&net_message);
2677 // if client is already spawned, re-send the
2678 // serverinfo message as they'll need it to play
2679 if (client->spawned)
2682 SV_SendServerinfo(client);
2689 // this is a new client, check for connection flood
2690 if (NetConn_PreventConnectFlood(peeraddress))
2693 // find a slot for the new client
2694 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2697 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2699 // connect to the client
2700 // everything is allocated, just fill in the details
2701 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2702 if (developer.integer >= 10)
2703 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2704 // send back the info about the server connection
2705 SZ_Clear(&net_message);
2706 // save space for the header, filled in later
2707 MSG_WriteLong(&net_message, 0);
2708 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2709 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2710 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2711 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2712 SZ_Clear(&net_message);
2713 // now set up the client struct
2715 SV_ConnectClient(clientnum, conn);
2717 NetConn_Heartbeat(1);
2722 if (developer.integer >= 10)
2723 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2724 // no room; try to let player know
2725 SZ_Clear(&net_message);
2726 // save space for the header, filled in later
2727 MSG_WriteLong(&net_message, 0);
2728 MSG_WriteByte(&net_message, CCREP_REJECT);
2729 MSG_WriteString(&net_message, "Server is full.\n");
2730 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2731 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2732 SZ_Clear(&net_message);
2734 case CCREQ_SERVER_INFO:
2735 if (developer.integer >= 10)
2736 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2737 if(!islocal && sv_public.integer <= -1)
2739 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2742 char myaddressstring[128];
2743 if (developer.integer >= 10)
2744 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2745 SZ_Clear(&net_message);
2746 // save space for the header, filled in later
2747 MSG_WriteLong(&net_message, 0);
2748 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2749 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2750 MSG_WriteString(&net_message, myaddressstring);
2751 MSG_WriteString(&net_message, hostname.string);
2752 MSG_WriteString(&net_message, sv.name);
2753 // How many clients are there?
2754 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2755 if (svs.clients[i].active)
2757 MSG_WriteByte(&net_message, numclients);
2758 MSG_WriteByte(&net_message, svs.maxclients);
2759 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2760 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2761 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2762 SZ_Clear(&net_message);
2765 case CCREQ_PLAYER_INFO:
2766 if (developer.integer >= 10)
2767 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2768 if(!islocal && sv_public.integer <= -1)
2772 int playerNumber, activeNumber, clientNumber;
2775 playerNumber = MSG_ReadByte();
2777 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2778 if (client->active && ++activeNumber == playerNumber)
2780 if (clientNumber != svs.maxclients)
2782 SZ_Clear(&net_message);
2783 // save space for the header, filled in later
2784 MSG_WriteLong(&net_message, 0);
2785 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2786 MSG_WriteByte(&net_message, playerNumber);
2787 MSG_WriteString(&net_message, client->name);
2788 MSG_WriteLong(&net_message, client->colors);
2789 MSG_WriteLong(&net_message, client->frags);
2790 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2791 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2792 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2793 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2794 SZ_Clear(&net_message);
2798 case CCREQ_RULE_INFO:
2799 if (developer.integer >= 10)
2800 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2801 if(!islocal && sv_public.integer <= -1)
2808 // find the search start location
2809 prevCvarName = MSG_ReadString();
2810 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2812 // send the response
2813 SZ_Clear(&net_message);
2814 // save space for the header, filled in later
2815 MSG_WriteLong(&net_message, 0);
2816 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2819 MSG_WriteString(&net_message, var->name);
2820 MSG_WriteString(&net_message, var->string);
2822 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2823 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2824 SZ_Clear(&net_message);
2830 SZ_Clear(&net_message);
2831 // we may not have liked the packet, but it was a valid control
2832 // packet, so we're done processing this packet now
2837 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2840 SV_ReadClientMessage();
2848 void NetConn_ServerFrame(void)
2851 lhnetaddress_t peeraddress;
2852 for (i = 0;i < sv_numsockets;i++)
2853 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2854 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2855 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2857 // never timeout loopback connections
2858 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2860 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2862 SV_DropClient(false);
2868 void NetConn_SleepMicroseconds(int microseconds)
2870 LHNET_SleepUntilPacket_Microseconds(microseconds);
2873 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2877 lhnetaddress_t masteraddress;
2878 lhnetaddress_t broadcastaddress;
2881 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2884 // 26000 is the default quake server port, servers on other ports will not
2886 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2887 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2891 for (i = 0;i < cl_numsockets;i++)
2895 const char *cmdname, *extraoptions;
2896 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2898 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2900 // search LAN for Quake servers
2901 SZ_Clear(&net_message);
2902 // save space for the header, filled in later
2903 MSG_WriteLong(&net_message, 0);
2904 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2905 MSG_WriteString(&net_message, "QUAKE");
2906 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2907 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2908 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2909 SZ_Clear(&net_message);
2911 // search LAN for DarkPlaces servers
2912 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2915 // build the getservers message to send to the dpmaster master servers
2916 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
2918 cmdname = "getserversExt";
2919 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
2923 cmdname = "getservers";
2926 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
2929 for (masternum = 0;sv_masters[masternum].name;masternum++)
2931 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2934 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2938 // search favorite servers
2939 for(j = 0; j < nFavorites; ++j)
2941 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2943 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2944 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
2951 // only query QuakeWorld servers when the user wants to
2954 for (i = 0;i < cl_numsockets;i++)
2958 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2960 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2962 // search LAN for QuakeWorld servers
2963 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2965 // build the getservers message to send to the qwmaster master servers
2966 // note this has no -1 prefix, and the trailing nul byte is sent
2967 dpsnprintf(request, sizeof(request), "c\n");
2971 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2973 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2975 if (m_state != m_slist)
2977 char lookupstring[128];
2978 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2979 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2982 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2986 // search favorite servers
2987 for(j = 0; j < nFavorites; ++j)
2989 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2991 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2993 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
2994 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3001 if (!masterquerycount)
3003 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3004 M_Update_Return_Reason("No network");
3008 void NetConn_Heartbeat(int priority)
3010 lhnetaddress_t masteraddress;
3012 lhnetsocket_t *mysocket;
3014 // if it's a state change (client connected), limit next heartbeat to no
3015 // more than 30 sec in the future
3016 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3017 nextheartbeattime = realtime + 30.0;
3019 // limit heartbeatperiod to 30 to 270 second range,
3020 // lower limit is to avoid abusing master servers with excess traffic,
3021 // upper limit is to avoid timing out on the master server (which uses
3023 if (sv_heartbeatperiod.value < 30)
3024 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3025 if (sv_heartbeatperiod.value > 270)
3026 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3028 // make advertising optional and don't advertise singleplayer games, and
3029 // only send a heartbeat as often as the admin wants
3030 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3032 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3033 for (masternum = 0;sv_masters[masternum].name;masternum++)
3034 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3035 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3039 static void Net_Heartbeat_f(void)
3042 NetConn_Heartbeat(2);
3044 Con_Print("No server running, can not heartbeat to master server.\n");
3047 void PrintStats(netconn_t *conn)
3049 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3050 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3052 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3055 void Net_Stats_f(void)
3058 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3059 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3060 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3061 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3062 Con_Printf("packetsSent = %i\n", packetsSent);
3063 Con_Printf("packetsReSent = %i\n", packetsReSent);
3064 Con_Printf("packetsReceived = %i\n", packetsReceived);
3065 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3066 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3067 Con_Print("connections =\n");
3068 for (conn = netconn_list;conn;conn = conn->next)
3072 void Net_Refresh_f(void)
3074 if (m_state != m_slist) {
3075 Con_Print("Sending new requests to master servers\n");
3076 ServerList_QueryList(false, true, false, true);
3077 Con_Print("Listening for replies...\n");
3079 ServerList_QueryList(false, true, false, false);
3082 void Net_Slist_f(void)
3084 ServerList_ResetMasks();
3085 serverlist_sortbyfield = SLIF_PING;
3086 serverlist_sortflags = 0;
3087 if (m_state != m_slist) {
3088 Con_Print("Sending requests to master servers\n");
3089 ServerList_QueryList(true, true, false, true);
3090 Con_Print("Listening for replies...\n");
3092 ServerList_QueryList(true, true, false, false);
3095 void Net_SlistQW_f(void)
3097 ServerList_ResetMasks();
3098 serverlist_sortbyfield = SLIF_PING;
3099 serverlist_sortflags = 0;
3100 if (m_state != m_slist) {
3101 Con_Print("Sending requests to master servers\n");
3102 ServerList_QueryList(true, false, true, true);
3103 serverlist_consoleoutput = true;
3104 Con_Print("Listening for replies...\n");
3106 ServerList_QueryList(true, false, true, false);
3109 void NetConn_Init(void)
3112 lhnetaddress_t tempaddress;
3113 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3114 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3115 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3116 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3117 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3118 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3119 Cvar_RegisterVariable(&rcon_restricted_password);
3120 Cvar_RegisterVariable(&rcon_restricted_commands);
3121 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3122 Cvar_RegisterVariable(&net_slist_queriespersecond);
3123 Cvar_RegisterVariable(&net_slist_queriesperframe);
3124 Cvar_RegisterVariable(&net_slist_timeout);
3125 Cvar_RegisterVariable(&net_slist_maxtries);
3126 Cvar_RegisterVariable(&net_slist_favorites);
3127 Cvar_RegisterVariable(&net_slist_pause);
3128 Cvar_RegisterVariable(&net_messagetimeout);
3129 Cvar_RegisterVariable(&net_connecttimeout);
3130 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3131 Cvar_RegisterVariable(&cl_netlocalping);
3132 Cvar_RegisterVariable(&cl_netpacketloss_send);
3133 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3134 Cvar_RegisterVariable(&hostname);
3135 Cvar_RegisterVariable(&developer_networking);
3136 Cvar_RegisterVariable(&cl_netport);
3137 Cvar_RegisterVariable(&sv_netport);
3138 Cvar_RegisterVariable(&net_address);
3139 Cvar_RegisterVariable(&net_address_ipv6);
3140 Cvar_RegisterVariable(&sv_public);
3141 Cvar_RegisterVariable(&sv_heartbeatperiod);
3142 for (i = 0;sv_masters[i].name;i++)
3143 Cvar_RegisterVariable(&sv_masters[i]);
3144 Cvar_RegisterVariable(&gameversion);
3145 // 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.
3146 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3148 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3150 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3151 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3154 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3156 // 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
3157 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3159 i = atoi(com_argv[i + 1]);
3160 if (i >= 0 && i < 65536)
3162 Con_Printf("-port option used, setting port cvar to %i\n", i);
3163 Cvar_SetValueQuick(&sv_netport, i);
3166 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3170 net_message.data = net_message_buf;
3171 net_message.maxsize = sizeof(net_message_buf);
3172 net_message.cursize = 0;
3176 void NetConn_Shutdown(void)
3178 NetConn_CloseClientPorts();
3179 NetConn_CloseServerPorts();