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", "0.0.0.0", "network address to open ports on"};
130 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
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, int defaultport)
832 lhnetaddress_t address;
834 char addressstring2[1024];
835 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
837 if ((s = LHNET_OpenSocket_Connectionless(&address)))
839 cl_sockets[cl_numsockets++] = s;
840 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
841 Con_Printf("Client opened a socket on address %s\n", addressstring2);
845 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
846 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
850 Con_Printf("Client unable to parse address %s\n", addressstring);
853 void NetConn_OpenClientPorts(void)
856 NetConn_CloseClientPorts();
857 port = bound(0, cl_netport.integer, 65535);
858 if (cl_netport.integer != port)
859 Cvar_SetValueQuick(&cl_netport, port);
861 Con_Printf("Client using an automatically assigned port\n");
863 Con_Printf("Client using port %i\n", port);
864 NetConn_OpenClientPort("local:2", 0);
865 NetConn_OpenClientPort(net_address.string, port);
866 //NetConn_OpenClientPort(net_address_ipv6.string, port);
869 void NetConn_CloseServerPorts(void)
871 for (;sv_numsockets > 0;sv_numsockets--)
872 if (sv_sockets[sv_numsockets - 1])
873 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
876 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
878 lhnetaddress_t address;
881 char addressstring2[1024];
883 for (port = defaultport; port <= defaultport + 100; port++)
885 if (LHNETADDRESS_FromString(&address, addressstring, port))
887 if ((s = LHNET_OpenSocket_Connectionless(&address)))
889 sv_sockets[sv_numsockets++] = s;
890 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
891 Con_Printf("Server listening on address %s\n", addressstring2);
896 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
897 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
902 Con_Printf("Server unable to parse address %s\n", addressstring);
903 // if it cant parse one address, it wont be able to parse another for sure
909 void NetConn_OpenServerPorts(int opennetports)
912 NetConn_CloseServerPorts();
913 NetConn_UpdateSockets();
914 port = bound(0, sv_netport.integer, 65535);
917 Con_Printf("Server using port %i\n", port);
918 if (sv_netport.integer != port)
919 Cvar_SetValueQuick(&sv_netport, port);
920 if (cls.state != ca_dedicated)
921 NetConn_OpenServerPort("local:1", 0);
924 NetConn_OpenServerPort(net_address.string, port);
925 //NetConn_OpenServerPort(net_address_ipv6.string, port);
927 if (sv_numsockets == 0)
928 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
931 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
933 int i, a = LHNETADDRESS_GetAddressType(address);
934 for (i = 0;i < cl_numsockets;i++)
935 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
936 return cl_sockets[i];
940 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
942 int i, a = LHNETADDRESS_GetAddressType(address);
943 for (i = 0;i < sv_numsockets;i++)
944 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
945 return sv_sockets[i];
949 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
952 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
953 conn->mysocket = mysocket;
954 conn->peeraddress = *peeraddress;
955 conn->lastMessageTime = realtime;
956 conn->message.data = conn->messagedata;
957 conn->message.maxsize = sizeof(conn->messagedata);
958 conn->message.cursize = 0;
959 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
960 // reduce effectiveness of connection request floods
961 conn->timeout = realtime + net_connecttimeout.value;
962 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
963 conn->next = netconn_list;
968 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
969 void NetConn_Close(netconn_t *conn)
972 // remove connection from list
974 // allow the client to reconnect immediately
975 NetConn_ClearConnectFlood(&(conn->peeraddress));
977 if (conn == netconn_list)
978 netconn_list = conn->next;
981 for (c = netconn_list;c;c = c->next)
985 c->next = conn->next;
989 // not found in list, we'll avoid crashing here...
997 static int clientport = -1;
998 static int clientport2 = -1;
999 static int hostport = -1;
1000 void NetConn_UpdateSockets(void)
1002 if (cls.state != ca_dedicated)
1004 if (clientport2 != cl_netport.integer)
1006 clientport2 = cl_netport.integer;
1007 if (cls.state == ca_connected)
1008 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1010 if (cls.state == ca_disconnected && clientport != clientport2)
1012 clientport = clientport2;
1013 NetConn_CloseClientPorts();
1015 if (cl_numsockets == 0)
1016 NetConn_OpenClientPorts();
1019 if (hostport != sv_netport.integer)
1021 hostport = sv_netport.integer;
1023 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1027 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1029 int originallength = length;
1033 if (protocol == PROTOCOL_QUAKEWORLD)
1035 int sequence, sequence_ack;
1036 int reliable_ack, reliable_message;
1040 sequence = LittleLong(*((int *)(data + 0)));
1041 sequence_ack = LittleLong(*((int *)(data + 4)));
1045 if (conn != cls.netcon)
1050 // 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?)
1051 qport = LittleShort(*((int *)(data + 8)));
1057 reliable_message = (sequence >> 31) & 1;
1058 reliable_ack = (sequence_ack >> 31) & 1;
1059 sequence &= ~(1<<31);
1060 sequence_ack &= ~(1<<31);
1061 if (sequence <= conn->qw.incoming_sequence)
1063 //Con_DPrint("Got a stale datagram\n");
1066 count = sequence - (conn->qw.incoming_sequence + 1);
1069 droppedDatagrams += count;
1070 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1073 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1074 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1075 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1076 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1079 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1080 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1081 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1082 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1083 if (reliable_ack == conn->qw.reliable_sequence)
1085 // received, now we will be able to send another reliable message
1086 conn->sendMessageLength = 0;
1087 reliableMessagesReceived++;
1089 conn->qw.incoming_sequence = sequence;
1090 if (conn == cls.netcon)
1091 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1092 conn->qw.incoming_acknowledged = sequence_ack;
1093 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1094 if (reliable_message)
1095 conn->qw.incoming_reliable_sequence ^= 1;
1096 conn->lastMessageTime = realtime;
1097 conn->timeout = realtime + newtimeout;
1098 unreliableMessagesReceived++;
1099 SZ_Clear(&net_message);
1100 SZ_Write(&net_message, data, length);
1108 unsigned int sequence;
1111 qlength = (unsigned int)BigLong(((int *)data)[0]);
1112 flags = qlength & ~NETFLAG_LENGTH_MASK;
1113 qlength &= NETFLAG_LENGTH_MASK;
1114 // control packets were already handled
1115 if (!(flags & NETFLAG_CTL) && qlength == length)
1117 sequence = BigLong(((int *)data)[1]);
1121 if (flags & NETFLAG_UNRELIABLE)
1123 if (sequence >= conn->nq.unreliableReceiveSequence)
1125 if (sequence > conn->nq.unreliableReceiveSequence)
1127 count = sequence - conn->nq.unreliableReceiveSequence;
1128 droppedDatagrams += count;
1129 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1132 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1133 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1134 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1135 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1138 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1139 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1140 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1141 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1142 conn->nq.unreliableReceiveSequence = sequence + 1;
1143 conn->lastMessageTime = realtime;
1144 conn->timeout = realtime + newtimeout;
1145 unreliableMessagesReceived++;
1148 SZ_Clear(&net_message);
1149 SZ_Write(&net_message, data, length);
1155 // Con_DPrint("Got a stale datagram\n");
1158 else if (flags & NETFLAG_ACK)
1160 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1161 if (sequence == (conn->nq.sendSequence - 1))
1163 if (sequence == conn->nq.ackSequence)
1165 conn->nq.ackSequence++;
1166 if (conn->nq.ackSequence != conn->nq.sendSequence)
1167 Con_DPrint("ack sequencing error\n");
1168 conn->lastMessageTime = realtime;
1169 conn->timeout = realtime + newtimeout;
1170 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1172 unsigned int packetLen;
1173 unsigned int dataLen;
1175 unsigned int *header;
1177 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1178 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1180 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1182 dataLen = conn->sendMessageLength;
1187 dataLen = MAX_PACKETFRAGMENT;
1191 packetLen = NET_HEADERSIZE + dataLen;
1193 header = (unsigned int *)sendbuffer;
1194 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1195 header[1] = BigLong(conn->nq.sendSequence);
1196 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1198 conn->nq.sendSequence++;
1200 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1202 conn->lastSendTime = realtime;
1207 conn->sendMessageLength = 0;
1210 // Con_DPrint("Duplicate ACK received\n");
1213 // Con_DPrint("Stale ACK received\n");
1216 else if (flags & NETFLAG_DATA)
1218 unsigned int temppacket[2];
1219 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1220 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1221 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1222 temppacket[1] = BigLong(sequence);
1223 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1224 if (sequence == conn->nq.receiveSequence)
1226 conn->lastMessageTime = realtime;
1227 conn->timeout = realtime + newtimeout;
1228 conn->nq.receiveSequence++;
1229 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1230 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1231 conn->receiveMessageLength += length;
1233 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1234 "Dropping the message!\n", sequence );
1235 conn->receiveMessageLength = 0;
1238 if (flags & NETFLAG_EOM)
1240 reliableMessagesReceived++;
1241 length = conn->receiveMessageLength;
1242 conn->receiveMessageLength = 0;
1245 SZ_Clear(&net_message);
1246 SZ_Write(&net_message, conn->receiveMessage, length);
1253 receivedDuplicateCount++;
1261 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1263 cls.connect_trying = false;
1264 M_Update_Return_Reason("");
1265 // the connection request succeeded, stop current connection and set up a new connection
1267 // if we're connecting to a remote server, shut down any local server
1268 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1269 Host_ShutdownServer ();
1270 // allocate a net connection to keep track of things
1271 cls.netcon = NetConn_Open(mysocket, peeraddress);
1272 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1273 key_dest = key_game;
1275 cls.demonum = -1; // not in the demo loop now
1276 cls.state = ca_connected;
1277 cls.signon = 0; // need all the signon messages before playing
1278 cls.protocol = initialprotocol;
1279 // reset move sequence numbering on this new connection
1280 cls.servermovesequence = 0;
1281 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1282 Cmd_ForwardStringToServer("new");
1283 if (cls.protocol == PROTOCOL_QUAKE)
1285 // write a keepalive (clc_nop) as it seems to greatly improve the
1286 // chances of connecting to a netquake server
1288 unsigned char buf[4];
1289 memset(&msg, 0, sizeof(msg));
1291 msg.maxsize = sizeof(buf);
1292 MSG_WriteChar(&msg, clc_nop);
1293 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1297 int NetConn_IsLocalGame(void)
1299 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1304 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1308 serverlist_entry_t *entry = NULL;
1310 // search the cache for this server and update it
1311 for (n = 0;n < serverlist_cachecount;n++) {
1312 entry = &serverlist_cache[ n ];
1313 if (!strcmp(addressstring, entry->info.cname))
1317 if (n == serverlist_cachecount)
1319 // LAN search doesnt require an answer from the master server so we wont
1320 // know the ping nor will it be initialized already...
1323 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1326 entry = &serverlist_cache[n];
1328 memset(entry, 0, sizeof(*entry));
1329 // store the data the engine cares about (address and ping)
1330 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1331 entry->info.ping = 100000;
1332 entry->querytime = realtime;
1333 // if not in the slist menu we should print the server to console
1334 if (serverlist_consoleoutput)
1335 Con_Printf("querying %s\n", addressstring);
1336 ++serverlist_cachecount;
1338 // if this is the first reply from this server, count it as having replied
1339 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1340 pingtime = bound(0, pingtime, 9999);
1341 if (entry->query == SQS_REFRESHING) {
1342 entry->info.ping = pingtime;
1343 entry->query = SQS_QUERIED;
1345 // convert to unsigned to catch the -1
1346 // 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]
1347 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1351 // other server info is updated by the caller
1355 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1357 serverlist_entry_t *entry = &serverlist_cache[n];
1358 serverlist_info_t *info = &entry->info;
1359 // update description strings for engine menu and console output
1360 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);
1361 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);
1362 if (entry->query == SQS_QUERIED)
1364 if(!serverlist_paused)
1365 ServerList_ViewList_Remove(entry);
1367 // if not in the slist menu we should print the server to console (if wanted)
1368 else if( serverlist_consoleoutput )
1369 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1370 // and finally, update the view set
1371 if(!serverlist_paused)
1372 ServerList_ViewList_Insert( entry );
1373 // update the entry's state
1374 serverlist_cache[n].query = SQS_QUERIED;
1377 // returns true, if it's sensible to continue the processing
1378 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1380 serverlist_entry_t *entry;
1382 // ignore the rest of the message if the serverlist is full
1383 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1385 // also ignore it if we have already queried it (other master server response)
1386 for( n = 0 ; n < serverlist_cachecount ; n++ )
1387 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1390 entry = &serverlist_cache[n];
1392 if( n < serverlist_cachecount ) {
1393 // the entry has already been queried once or
1397 memset(entry, 0, sizeof(entry));
1398 entry->protocol = protocol;
1399 // store the data the engine cares about (address and ping)
1400 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1402 entry->info.isfavorite = isfavorite;
1404 // no, then reset the ping right away
1405 entry->info.ping = -1;
1406 // we also want to increase the serverlist_cachecount then
1407 serverlist_cachecount++;
1410 entry->query = SQS_QUERYING;
1415 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1417 qboolean fromserver;
1418 int ret, c, control;
1420 char *string, addressstring2[128], ipstring[32];
1421 char stringbuf[16384];
1423 // quakeworld ingame packet
1424 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1426 // convert the address to a string incase we need it
1427 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1429 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1431 // received a command string - strip off the packaging and put it
1432 // into our string buffer with NULL termination
1435 length = min(length, (int)sizeof(stringbuf) - 1);
1436 memcpy(stringbuf, data, length);
1437 stringbuf[length] = 0;
1440 if (developer_networking.integer)
1442 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1443 Com_HexDumpToConsole(data, length);
1446 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1448 // darkplaces or quake3
1449 char protocolnames[1400];
1450 Protocol_Names(protocolnames, sizeof(protocolnames));
1451 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1452 M_Update_Return_Reason("Got challenge response");
1453 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1454 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1455 // TODO: add userinfo stuff here instead of using NQ commands?
1456 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1459 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1461 // darkplaces or quake3
1462 M_Update_Return_Reason("Accepted");
1463 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1466 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1468 char rejectreason[32];
1469 cls.connect_trying = false;
1471 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1472 memcpy(rejectreason, string, length);
1473 rejectreason[length] = 0;
1474 M_Update_Return_Reason(rejectreason);
1477 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1479 serverlist_info_t *info;
1484 // search the cache for this server and update it
1485 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1489 info = &serverlist_cache[n].info;
1494 info->qcstatus[0] = 0;
1495 info->players[0] = 0;
1496 info->protocol = -1;
1497 info->numplayers = 0;
1499 info->maxplayers = 0;
1500 info->gameversion = 0;
1502 p = strchr(string, '\n');
1505 *p = 0; // cut off the string there
1509 Con_Printf("statusResponse without players block?\n");
1511 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1512 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1513 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1514 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1515 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1516 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1517 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1518 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1519 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1520 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1521 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1522 info->numhumans = info->numplayers - max(0, info->numbots);
1523 info->freeslots = info->maxplayers - info->numplayers;
1525 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1529 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1531 serverlist_info_t *info;
1535 // search the cache for this server and update it
1536 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1540 info = &serverlist_cache[n].info;
1545 info->qcstatus[0] = 0;
1546 info->players[0] = 0;
1547 info->protocol = -1;
1548 info->numplayers = 0;
1550 info->maxplayers = 0;
1551 info->gameversion = 0;
1553 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1554 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1555 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1556 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1557 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1558 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1559 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1560 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1561 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1562 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1563 info->numhumans = info->numplayers - max(0, info->numbots);
1564 info->freeslots = info->maxplayers - info->numplayers;
1566 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1570 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1572 // Extract the IP addresses
1576 if (serverlist_consoleoutput)
1577 Con_Print("received DarkPlaces server list...\n");
1578 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1580 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1581 if (serverlist_consoleoutput && developer_networking.integer)
1582 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1584 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1588 // move on to next address in packet
1592 // begin or resume serverlist queries
1593 serverlist_querysleep = false;
1594 serverlist_querywaittime = realtime + 3;
1597 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1599 // Extract the IP addresses
1603 if (serverlist_consoleoutput)
1604 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1605 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1607 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1608 if (serverlist_consoleoutput && developer_networking.integer)
1609 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1611 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1615 // move on to next address in packet
1619 // begin or resume serverlist queries
1620 serverlist_querysleep = false;
1621 serverlist_querywaittime = realtime + 3;
1624 if (!strncmp(string, "extResponse ", 12))
1626 ++net_extresponse_count;
1627 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1628 net_extresponse_count = NET_EXTRESPONSE_MAX;
1629 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1630 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1633 if (!strncmp(string, "ping", 4))
1635 if (developer.integer >= 10)
1636 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1637 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1640 if (!strncmp(string, "ack", 3))
1642 // QuakeWorld compatibility
1643 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1645 // challenge message
1646 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1647 M_Update_Return_Reason("Got QuakeWorld challenge response");
1648 cls.qw_qport = qport.integer;
1649 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1650 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1651 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1654 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1657 M_Update_Return_Reason("QuakeWorld Accepted");
1658 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1661 if (length > 2 && !memcmp(string, "n\\", 2))
1663 serverlist_info_t *info;
1667 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1668 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1671 // search the cache for this server and update it
1672 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1676 info = &serverlist_cache[n].info;
1677 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1678 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1679 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1680 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1682 info->numplayers = 0; // updated below
1683 info->numhumans = 0; // updated below
1684 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1685 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1687 // count active players on server
1688 // (we could gather more info, but we're just after the number)
1689 s = strchr(string, '\n');
1693 while (s < string + length)
1695 for (;s < string + length && *s != '\n';s++)
1697 if (s >= string + length)
1705 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1709 if (string[0] == 'n')
1712 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1714 // we may not have liked the packet, but it was a command packet, so
1715 // we're done processing this packet now
1718 // quakeworld ingame packet
1719 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1722 CL_ParseServerMessage();
1725 // netquake control packets, supported for compatibility only
1726 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1729 serverlist_info_t *info;
1733 SZ_Clear(&net_message);
1734 SZ_Write(&net_message, data, length);
1740 if (developer.integer >= 10)
1741 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1742 if (cls.connect_trying)
1744 lhnetaddress_t clientportaddress;
1745 clientportaddress = *peeraddress;
1746 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1747 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1748 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1749 M_Update_Return_Reason("Accepted");
1750 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1754 if (developer.integer >= 10)
1755 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1756 cls.connect_trying = false;
1757 M_Update_Return_Reason((char *)MSG_ReadString());
1759 case CCREP_SERVER_INFO:
1760 if (developer.integer >= 10)
1761 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1762 // LordHavoc: because the quake server may report weird addresses
1763 // we just ignore it and keep the real address
1765 // search the cache for this server and update it
1766 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1770 info = &serverlist_cache[n].info;
1771 strlcpy(info->game, "Quake", sizeof(info->game));
1772 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1773 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1774 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1775 info->numplayers = MSG_ReadByte();
1776 info->maxplayers = MSG_ReadByte();
1777 info->protocol = MSG_ReadByte();
1779 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1782 case CCREP_PLAYER_INFO:
1783 // we got a CCREP_PLAYER_INFO??
1784 //if (developer.integer >= 10)
1785 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1787 case CCREP_RULE_INFO:
1788 // we got a CCREP_RULE_INFO??
1789 //if (developer.integer >= 10)
1790 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1795 SZ_Clear(&net_message);
1796 // we may not have liked the packet, but it was a valid control
1797 // packet, so we're done processing this packet now
1801 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1802 CL_ParseServerMessage();
1806 void NetConn_QueryQueueFrame(void)
1812 static double querycounter = 0;
1814 if(!net_slist_pause.integer && serverlist_paused)
1815 ServerList_RebuildViewList();
1816 serverlist_paused = net_slist_pause.integer;
1818 if (serverlist_querysleep)
1821 // apply a cool down time after master server replies,
1822 // to avoid messing up the ping times on the servers
1823 if (serverlist_querywaittime > realtime)
1826 // each time querycounter reaches 1.0 issue a query
1827 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1828 maxqueries = (int)querycounter;
1829 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1830 querycounter -= maxqueries;
1832 if( maxqueries == 0 ) {
1836 // scan serverlist and issue queries as needed
1837 serverlist_querysleep = true;
1839 timeouttime = realtime - net_slist_timeout.value;
1840 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1842 serverlist_entry_t *entry = &serverlist_cache[ index ];
1843 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1848 serverlist_querysleep = false;
1849 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1854 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1856 lhnetaddress_t address;
1859 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1860 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1862 for (socket = 0; socket < cl_numsockets ; socket++)
1863 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1867 for (socket = 0; socket < cl_numsockets ; socket++)
1868 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1871 // update the entry fields
1872 entry->querytime = realtime;
1873 entry->querycounter++;
1875 // if not in the slist menu we should print the server to console
1876 if (serverlist_consoleoutput)
1877 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1883 // have we tried to refresh this server?
1884 if( entry->query == SQS_REFRESHING ) {
1885 // yes, so update the reply count (since its not responding anymore)
1887 if(!serverlist_paused)
1888 ServerList_ViewList_Remove(entry);
1890 entry->query = SQS_TIMEDOUT;
1895 void NetConn_ClientFrame(void)
1898 lhnetaddress_t peeraddress;
1899 NetConn_UpdateSockets();
1900 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1902 if (cls.connect_remainingtries == 0)
1903 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1904 cls.connect_nextsendtime = realtime + 1;
1905 cls.connect_remainingtries--;
1906 if (cls.connect_remainingtries <= -10)
1908 cls.connect_trying = false;
1909 M_Update_Return_Reason("Connect: Failed");
1912 // try challenge first (newer DP server or QW)
1913 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1914 // then try netquake as a fallback (old server, or netquake)
1915 SZ_Clear(&net_message);
1916 // save space for the header, filled in later
1917 MSG_WriteLong(&net_message, 0);
1918 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1919 MSG_WriteString(&net_message, "QUAKE");
1920 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1921 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1922 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1923 SZ_Clear(&net_message);
1925 for (i = 0;i < cl_numsockets;i++)
1926 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1927 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1928 NetConn_QueryQueueFrame();
1929 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1931 Con_Print("Connection timed out\n");
1933 Host_ShutdownServer ();
1937 #define MAX_CHALLENGES 128
1940 lhnetaddress_t address;
1944 challenge[MAX_CHALLENGES];
1946 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1950 for (i = 0;i < bufferlength - 1;i++)
1954 c = rand () % (127 - 33) + 33;
1955 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1961 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
1962 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1965 unsigned int nb_clients = 0, nb_bots = 0, i;
1971 // How many clients are there?
1972 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1974 if (svs.clients[i].active)
1977 if (!svs.clients[i].netconnection)
1983 if(prog->globaloffsets.worldstatus >= 0)
1985 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
1991 for(q = str; *q; ++q)
1992 if(*q != '\\' && *q != '\n')
1998 // TODO: we should add more information for the full status string
1999 length = dpsnprintf(out_msg, out_size,
2000 "\377\377\377\377%s\x0A"
2001 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2002 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2006 fullstatus ? "statusResponse" : "infoResponse",
2007 gamename, com_modname, gameversion.integer, svs.maxclients,
2008 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2009 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2010 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2011 fullstatus ? "\n" : "");
2013 // Make sure it fits in the buffer
2023 savelength = length;
2025 ptr = out_msg + length;
2026 left = (int)out_size - length;
2028 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2030 client_t *cl = &svs.clients[i];
2033 int nameind, cleanind, pingvalue;
2035 char cleanname [sizeof(cl->name)];
2037 // Remove all characters '"' and '\' in the player name
2042 curchar = cl->name[nameind++];
2043 if (curchar != '"' && curchar != '\\')
2045 cleanname[cleanind++] = curchar;
2046 if (cleanind == sizeof(cleanname) - 1)
2049 } while (curchar != '\0');
2050 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2052 pingvalue = (int)(cl->ping * 1000.0f);
2053 if(cl->netconnection)
2054 pingvalue = bound(1, pingvalue, 9999);
2059 if(prog->fieldoffsets.clientstatus >= 0)
2061 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2067 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2068 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2074 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2076 if(cl->frags == -666) // spectator
2077 strlcpy(teambuf, " 0", sizeof(teambuf));
2078 else if(cl->colors == 0x44) // red team
2079 strlcpy(teambuf, " 1", sizeof(teambuf));
2080 else if(cl->colors == 0xDD) // blue team
2081 strlcpy(teambuf, " 2", sizeof(teambuf));
2082 else if(cl->colors == 0xCC) // yellow team
2083 strlcpy(teambuf, " 3", sizeof(teambuf));
2084 else if(cl->colors == 0x99) // pink team
2085 strlcpy(teambuf, " 4", sizeof(teambuf));
2087 strlcpy(teambuf, " 0", sizeof(teambuf));
2092 // note: team number is inserted according to SoF2 protocol
2094 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2100 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2109 // turn it into an infoResponse!
2110 out_msg[savelength] = 0;
2111 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2112 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2129 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2131 int floodslotnum, bestfloodslotnum;
2132 double bestfloodtime;
2133 lhnetaddress_t noportpeeraddress;
2134 // see if this is a connect flood
2135 noportpeeraddress = *peeraddress;
2136 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2137 bestfloodslotnum = 0;
2138 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2139 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2141 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2143 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2144 bestfloodslotnum = floodslotnum;
2146 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2148 // this address matches an ongoing flood address
2149 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2151 // renew the ban on this address so it does not expire
2152 // until the flood has subsided
2153 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2154 //Con_Printf("Flood detected!\n");
2157 // the flood appears to have subsided, so allow this
2158 bestfloodslotnum = floodslotnum; // reuse the same slot
2162 // begin a new timeout on this address
2163 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2164 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2165 //Con_Printf("Flood detection initiated!\n");
2169 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2172 lhnetaddress_t noportpeeraddress;
2173 // see if this is a connect flood
2174 noportpeeraddress = *peeraddress;
2175 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2176 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2178 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2180 // this address matches an ongoing flood address
2182 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2183 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2184 //Con_Printf("Flood cleared!\n");
2189 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2191 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2196 t1 = (long) time(NULL);
2197 t2 = strtol(s, NULL, 0);
2198 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2201 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2204 return !memcmp(mdfourbuf, hash, 16);
2207 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2209 return !strcmp(password, hash);
2212 // returns a string describing the user level, or NULL for auth failure
2213 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2218 if(comparator(rcon_password.string, password, cs, cslen))
2221 if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2224 for(text = s; text != endpos; ++text)
2225 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2226 return NULL; // block possible exploits against the parser/alias expansion
2230 size_t l = strlen(s);
2233 hasquotes = (strchr(s, '"') != NULL);
2234 // sorry, we can't allow these substrings in wildcard expressions,
2235 // as they can mess with the argument counts
2236 text = rcon_restricted_commands.string;
2237 while(COM_ParseToken_Console(&text))
2239 // com_token now contains a pattern to check for...
2240 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2243 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2246 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2248 if(!strcmp(com_token, s))
2251 else // single-arg expression? must match the beginning of the command
2253 if(!strcmp(com_token, s))
2255 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2259 // if we got here, nothing matched!
2266 return "restricted rcon";
2269 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2273 // looks like a legitimate rcon command with the correct password
2274 const char *s_ptr = s;
2275 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2276 while(s_ptr != endpos)
2278 size_t l = strlen(s_ptr);
2280 Con_Printf(" %s;", s_ptr);
2285 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2286 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2289 size_t l = strlen(s);
2292 client_t *host_client_save = host_client;
2293 Cmd_ExecuteString(s, src_command);
2294 host_client = host_client_save;
2295 // in case it is a command that changes host_client (like restart)
2299 Con_Rcon_Redirect_End();
2303 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2307 extern void SV_SendServerinfo (client_t *client);
2308 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2310 int i, ret, clientnum, best;
2313 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2314 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2319 // convert the address to a string incase we need it
2320 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2322 // see if we can identify the sender as a local player
2323 // (this is necessary for rcon to send a reliable reply if the client is
2324 // actually on the server, not sending remotely)
2325 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2326 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2328 if (i == svs.maxclients)
2331 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2333 // received a command string - strip off the packaging and put it
2334 // into our string buffer with NULL termination
2337 length = min(length, (int)sizeof(stringbuf) - 1);
2338 memcpy(stringbuf, data, length);
2339 stringbuf[length] = 0;
2342 if (developer.integer >= 10)
2344 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2345 Com_HexDumpToConsole(data, length);
2348 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2350 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2352 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2354 if (besttime > challenge[i].time)
2355 besttime = challenge[best = i].time;
2357 // if we did not find an exact match, choose the oldest and
2358 // update address and string
2359 if (i == MAX_CHALLENGES)
2362 challenge[i].address = *peeraddress;
2363 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2365 challenge[i].time = realtime;
2366 // send the challenge
2367 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2370 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2375 if (!(s = SearchInfostring(string, "challenge")))
2377 // validate the challenge
2378 for (i = 0;i < MAX_CHALLENGES;i++)
2379 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2381 // if the challenge is not recognized, drop the packet
2382 if (i == MAX_CHALLENGES)
2385 // check engine protocol
2386 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2388 if (developer.integer >= 10)
2389 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2390 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2394 // see if this is a duplicate connection request or a disconnected
2395 // client who is rejoining to the same client slot
2396 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2398 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2400 // this is a known client...
2401 if (client->spawned)
2403 // client crashed and is coming back,
2404 // keep their stuff intact
2405 if (developer.integer >= 10)
2406 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2407 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2409 SV_SendServerinfo(client);
2414 // client is still trying to connect,
2415 // so we send a duplicate reply
2416 if (developer.integer >= 10)
2417 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2418 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2424 if (NetConn_PreventConnectFlood(peeraddress))
2427 // find an empty client slot for this new client
2428 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2431 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2433 // allocated connection
2434 if (developer.integer >= 10)
2435 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2436 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2437 // now set up the client
2439 SV_ConnectClient(clientnum, conn);
2441 NetConn_Heartbeat(1);
2446 // no empty slots found - server is full
2447 if (developer.integer >= 10)
2448 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2449 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2453 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2455 const char *challenge = NULL;
2457 // If there was a challenge in the getinfo message
2458 if (length > 8 && string[7] == ' ')
2459 challenge = string + 8;
2461 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2463 if (developer.integer >= 10)
2464 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2465 NetConn_WriteString(mysocket, response, peeraddress);
2469 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2471 const char *challenge = NULL;
2473 // If there was a challenge in the getinfo message
2474 if (length > 10 && string[9] == ' ')
2475 challenge = string + 10;
2477 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2479 if (developer.integer >= 10)
2480 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2481 NetConn_WriteString(mysocket, response, peeraddress);
2485 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2487 char *password = string + 20;
2488 char *timeval = string + 37;
2489 char *s = strchr(timeval, ' ');
2490 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2491 const char *userlevel;
2493 return true; // invalid packet
2496 userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2497 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2500 if (length >= 5 && !memcmp(string, "rcon ", 5))
2503 char *s = string + 5;
2504 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2507 if(rcon_secure.integer)
2510 for (i = 0;!ISWHITESPACE(*s);s++)
2511 if (i < (int)sizeof(password) - 1)
2513 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2516 if (!ISWHITESPACE(password[0]))
2518 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2519 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2523 if (!strncmp(string, "ping", 4))
2525 if (developer.integer >= 10)
2526 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2527 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2530 if (!strncmp(string, "ack", 3))
2532 // we may not have liked the packet, but it was a command packet, so
2533 // we're done processing this packet now
2536 // netquake control packets, supported for compatibility only, and only
2537 // when running game protocols that are normally served via this connection
2539 // (this protects more modern protocols against being used for
2540 // Quake packet flood Denial Of Service attacks)
2541 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))
2545 const char *protocolname;
2548 SZ_Clear(&net_message);
2549 SZ_Write(&net_message, data, length);
2555 if (developer.integer >= 10)
2556 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2557 if(!islocal && sv_public.integer <= -2)
2560 protocolname = MSG_ReadString();
2561 protocolnumber = MSG_ReadByte();
2562 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2564 if (developer.integer >= 10)
2565 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2566 SZ_Clear(&net_message);
2567 // save space for the header, filled in later
2568 MSG_WriteLong(&net_message, 0);
2569 MSG_WriteByte(&net_message, CCREP_REJECT);
2570 MSG_WriteString(&net_message, "Incompatible version.\n");
2571 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2572 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2573 SZ_Clear(&net_message);
2577 // see if this connect request comes from a known client
2578 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2580 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2582 // this is either a duplicate connection request
2583 // or coming back from a timeout
2584 // (if so, keep their stuff intact)
2587 if (developer.integer >= 10)
2588 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2589 SZ_Clear(&net_message);
2590 // save space for the header, filled in later
2591 MSG_WriteLong(&net_message, 0);
2592 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2593 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2594 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2595 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2596 SZ_Clear(&net_message);
2598 // if client is already spawned, re-send the
2599 // serverinfo message as they'll need it to play
2600 if (client->spawned)
2603 SV_SendServerinfo(client);
2610 // this is a new client, check for connection flood
2611 if (NetConn_PreventConnectFlood(peeraddress))
2614 // find a slot for the new client
2615 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2618 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2620 // connect to the client
2621 // everything is allocated, just fill in the details
2622 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2623 if (developer.integer >= 10)
2624 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2625 // send back the info about the server connection
2626 SZ_Clear(&net_message);
2627 // save space for the header, filled in later
2628 MSG_WriteLong(&net_message, 0);
2629 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2630 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2631 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2632 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2633 SZ_Clear(&net_message);
2634 // now set up the client struct
2636 SV_ConnectClient(clientnum, conn);
2638 NetConn_Heartbeat(1);
2643 if (developer.integer >= 10)
2644 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2645 // no room; try to let player know
2646 SZ_Clear(&net_message);
2647 // save space for the header, filled in later
2648 MSG_WriteLong(&net_message, 0);
2649 MSG_WriteByte(&net_message, CCREP_REJECT);
2650 MSG_WriteString(&net_message, "Server is full.\n");
2651 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2652 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2653 SZ_Clear(&net_message);
2655 case CCREQ_SERVER_INFO:
2656 if (developer.integer >= 10)
2657 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2658 if(!islocal && sv_public.integer <= -1)
2660 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2663 char myaddressstring[128];
2664 if (developer.integer >= 10)
2665 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2666 SZ_Clear(&net_message);
2667 // save space for the header, filled in later
2668 MSG_WriteLong(&net_message, 0);
2669 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2670 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2671 MSG_WriteString(&net_message, myaddressstring);
2672 MSG_WriteString(&net_message, hostname.string);
2673 MSG_WriteString(&net_message, sv.name);
2674 // How many clients are there?
2675 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2676 if (svs.clients[i].active)
2678 MSG_WriteByte(&net_message, numclients);
2679 MSG_WriteByte(&net_message, svs.maxclients);
2680 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2681 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2682 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2683 SZ_Clear(&net_message);
2686 case CCREQ_PLAYER_INFO:
2687 if (developer.integer >= 10)
2688 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2689 if(!islocal && sv_public.integer <= -1)
2693 int playerNumber, activeNumber, clientNumber;
2696 playerNumber = MSG_ReadByte();
2698 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2699 if (client->active && ++activeNumber == playerNumber)
2701 if (clientNumber != svs.maxclients)
2703 SZ_Clear(&net_message);
2704 // save space for the header, filled in later
2705 MSG_WriteLong(&net_message, 0);
2706 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2707 MSG_WriteByte(&net_message, playerNumber);
2708 MSG_WriteString(&net_message, client->name);
2709 MSG_WriteLong(&net_message, client->colors);
2710 MSG_WriteLong(&net_message, client->frags);
2711 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2712 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2713 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2714 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2715 SZ_Clear(&net_message);
2719 case CCREQ_RULE_INFO:
2720 if (developer.integer >= 10)
2721 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2722 if(!islocal && sv_public.integer <= -1)
2729 // find the search start location
2730 prevCvarName = MSG_ReadString();
2731 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2733 // send the response
2734 SZ_Clear(&net_message);
2735 // save space for the header, filled in later
2736 MSG_WriteLong(&net_message, 0);
2737 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2740 MSG_WriteString(&net_message, var->name);
2741 MSG_WriteString(&net_message, var->string);
2743 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2744 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2745 SZ_Clear(&net_message);
2751 SZ_Clear(&net_message);
2752 // we may not have liked the packet, but it was a valid control
2753 // packet, so we're done processing this packet now
2758 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2761 SV_ReadClientMessage();
2769 void NetConn_ServerFrame(void)
2772 lhnetaddress_t peeraddress;
2773 for (i = 0;i < sv_numsockets;i++)
2774 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2775 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2776 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2778 // never timeout loopback connections
2779 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2781 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2783 SV_DropClient(false);
2789 void NetConn_SleepMicroseconds(int microseconds)
2791 LHNET_SleepUntilPacket_Microseconds(microseconds);
2794 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2798 lhnetaddress_t masteraddress;
2799 lhnetaddress_t broadcastaddress;
2802 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2805 // 26000 is the default quake server port, servers on other ports will not
2807 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2808 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2812 for (i = 0;i < cl_numsockets;i++)
2816 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2818 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2820 // search LAN for Quake servers
2821 SZ_Clear(&net_message);
2822 // save space for the header, filled in later
2823 MSG_WriteLong(&net_message, 0);
2824 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2825 MSG_WriteString(&net_message, "QUAKE");
2826 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2827 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2828 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2829 SZ_Clear(&net_message);
2831 // search LAN for DarkPlaces servers
2832 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2835 // build the getservers message to send to the dpmaster master servers
2836 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2839 for (masternum = 0;sv_masters[masternum].name;masternum++)
2841 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2844 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2848 // search favorite servers
2849 for(j = 0; j < nFavorites; ++j)
2851 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2853 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2854 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
2861 // only query QuakeWorld servers when the user wants to
2864 for (i = 0;i < cl_numsockets;i++)
2868 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2870 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2872 // search LAN for QuakeWorld servers
2873 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2875 // build the getservers message to send to the qwmaster master servers
2876 // note this has no -1 prefix, and the trailing nul byte is sent
2877 dpsnprintf(request, sizeof(request), "c\n");
2881 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2883 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2885 if (m_state != m_slist)
2887 char lookupstring[128];
2888 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2889 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2892 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2896 // search favorite servers
2897 for(j = 0; j < nFavorites; ++j)
2899 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2901 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2903 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
2904 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
2911 if (!masterquerycount)
2913 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2914 M_Update_Return_Reason("No network");
2918 void NetConn_Heartbeat(int priority)
2920 lhnetaddress_t masteraddress;
2922 lhnetsocket_t *mysocket;
2924 // if it's a state change (client connected), limit next heartbeat to no
2925 // more than 30 sec in the future
2926 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2927 nextheartbeattime = realtime + 30.0;
2929 // limit heartbeatperiod to 30 to 270 second range,
2930 // lower limit is to avoid abusing master servers with excess traffic,
2931 // upper limit is to avoid timing out on the master server (which uses
2933 if (sv_heartbeatperiod.value < 30)
2934 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2935 if (sv_heartbeatperiod.value > 270)
2936 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2938 // make advertising optional and don't advertise singleplayer games, and
2939 // only send a heartbeat as often as the admin wants
2940 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2942 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2943 for (masternum = 0;sv_masters[masternum].name;masternum++)
2944 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2945 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2949 static void Net_Heartbeat_f(void)
2952 NetConn_Heartbeat(2);
2954 Con_Print("No server running, can not heartbeat to master server.\n");
2957 void PrintStats(netconn_t *conn)
2959 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2960 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
2962 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2965 void Net_Stats_f(void)
2968 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2969 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2970 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2971 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2972 Con_Printf("packetsSent = %i\n", packetsSent);
2973 Con_Printf("packetsReSent = %i\n", packetsReSent);
2974 Con_Printf("packetsReceived = %i\n", packetsReceived);
2975 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2976 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2977 Con_Print("connections =\n");
2978 for (conn = netconn_list;conn;conn = conn->next)
2982 void Net_Refresh_f(void)
2984 if (m_state != m_slist) {
2985 Con_Print("Sending new requests to master servers\n");
2986 ServerList_QueryList(false, true, false, true);
2987 Con_Print("Listening for replies...\n");
2989 ServerList_QueryList(false, true, false, false);
2992 void Net_Slist_f(void)
2994 ServerList_ResetMasks();
2995 serverlist_sortbyfield = SLIF_PING;
2996 serverlist_sortflags = 0;
2997 if (m_state != m_slist) {
2998 Con_Print("Sending requests to master servers\n");
2999 ServerList_QueryList(true, true, false, true);
3000 Con_Print("Listening for replies...\n");
3002 ServerList_QueryList(true, true, false, false);
3005 void Net_SlistQW_f(void)
3007 ServerList_ResetMasks();
3008 serverlist_sortbyfield = SLIF_PING;
3009 serverlist_sortflags = 0;
3010 if (m_state != m_slist) {
3011 Con_Print("Sending requests to master servers\n");
3012 ServerList_QueryList(true, false, true, true);
3013 serverlist_consoleoutput = true;
3014 Con_Print("Listening for replies...\n");
3016 ServerList_QueryList(true, false, true, false);
3019 void NetConn_Init(void)
3022 lhnetaddress_t tempaddress;
3023 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3024 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3025 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3026 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3027 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3028 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3029 Cvar_RegisterVariable(&rcon_restricted_password);
3030 Cvar_RegisterVariable(&rcon_restricted_commands);
3031 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3032 Cvar_RegisterVariable(&net_slist_queriespersecond);
3033 Cvar_RegisterVariable(&net_slist_queriesperframe);
3034 Cvar_RegisterVariable(&net_slist_timeout);
3035 Cvar_RegisterVariable(&net_slist_maxtries);
3036 Cvar_RegisterVariable(&net_slist_favorites);
3037 Cvar_RegisterVariable(&net_slist_pause);
3038 Cvar_RegisterVariable(&net_messagetimeout);
3039 Cvar_RegisterVariable(&net_connecttimeout);
3040 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3041 Cvar_RegisterVariable(&cl_netlocalping);
3042 Cvar_RegisterVariable(&cl_netpacketloss_send);
3043 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3044 Cvar_RegisterVariable(&hostname);
3045 Cvar_RegisterVariable(&developer_networking);
3046 Cvar_RegisterVariable(&cl_netport);
3047 Cvar_RegisterVariable(&sv_netport);
3048 Cvar_RegisterVariable(&net_address);
3049 //Cvar_RegisterVariable(&net_address_ipv6);
3050 Cvar_RegisterVariable(&sv_public);
3051 Cvar_RegisterVariable(&sv_heartbeatperiod);
3052 for (i = 0;sv_masters[i].name;i++)
3053 Cvar_RegisterVariable(&sv_masters[i]);
3054 Cvar_RegisterVariable(&gameversion);
3055 // 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.
3056 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3058 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3060 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3061 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3064 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3066 // 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
3067 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3069 i = atoi(com_argv[i + 1]);
3070 if (i >= 0 && i < 65536)
3072 Con_Printf("-port option used, setting port cvar to %i\n", i);
3073 Cvar_SetValueQuick(&sv_netport, i);
3076 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3080 net_message.data = net_message_buf;
3081 net_message.maxsize = sizeof(net_message_buf);
3082 net_message.cursize = 0;
3086 void NetConn_Shutdown(void)
3088 NetConn_CloseClientPorts();
3089 NetConn_CloseServerPorts();