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 #define QWMASTER_PORT 27000
27 #define DPMASTER_PORT 27950
29 // note this defaults on for dedicated servers, off for listen servers
30 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"};
31 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
33 static cvar_t sv_masters [] =
35 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
36 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
37 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
38 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
39 {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40 {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
41 {0, "sv_masterextra3", "dpmaster.tchr.no", "default master server 3 (admin: tChr)"}, // admin: tChr
45 static cvar_t sv_qwmasters [] =
47 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
48 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
49 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
50 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
51 {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
52 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
53 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
54 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
55 {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
59 static double nextheartbeattime = 0;
61 sizebuf_t net_message;
62 static unsigned char net_message_buf[NET_MAXMESSAGE];
64 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
65 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
66 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)"};
67 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
68 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
70 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)"};
71 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)"};
72 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)"};
73 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
74 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)"};
75 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
76 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"};
77 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)"};
79 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"};
80 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode"};
81 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
83 /* statistic counters */
84 static int packetsSent = 0;
85 static int packetsReSent = 0;
86 static int packetsReceived = 0;
87 static int receivedDuplicateCount = 0;
88 static int droppedDatagrams = 0;
90 static int unreliableMessagesSent = 0;
91 static int unreliableMessagesReceived = 0;
92 static int reliableMessagesSent = 0;
93 static int reliableMessagesReceived = 0;
95 double masterquerytime = -1000;
96 int masterquerycount = 0;
97 int masterreplycount = 0;
98 int serverquerycount = 0;
99 int serverreplycount = 0;
101 // this is only false if there are still servers left to query
102 static qboolean serverlist_querysleep = true;
103 static qboolean serverlist_paused = false;
104 // this is pushed a second or two ahead of realtime whenever a master server
105 // reply is received, to avoid issuing queries while master replies are still
106 // flooding in (which would make a mess of the ping times)
107 static double serverlist_querywaittime = 0;
109 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
110 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
112 static int cl_numsockets;
113 static lhnetsocket_t *cl_sockets[16];
114 static int sv_numsockets;
115 static lhnetsocket_t *sv_sockets[16];
117 netconn_t *netconn_list = NULL;
118 mempool_t *netconn_mempool = NULL;
120 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
121 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
122 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
123 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
125 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
126 int net_extresponse_count = 0;
127 int net_extresponse_last = 0;
129 // ServerList interface
130 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
131 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
133 serverlist_infofield_t serverlist_sortbyfield;
134 qboolean serverlist_sortdescending;
136 int serverlist_viewcount = 0;
137 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
139 int serverlist_cachecount;
140 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
142 qboolean serverlist_consoleoutput;
144 // helper function to insert a value into the viewset
145 // spare entries will be removed
146 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
149 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
150 i = serverlist_viewcount++;
152 i = SERVERLIST_VIEWLISTSIZE - 1;
155 for( ; i > index ; i-- )
156 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
158 serverlist_viewlist[index] = entry;
161 // we suppose serverlist_viewcount to be valid, ie > 0
162 static void _ServerList_ViewList_Helper_Remove( int index )
164 serverlist_viewcount--;
165 for( ; index < serverlist_viewcount ; index++ )
166 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
169 // returns true if A should be inserted before B
170 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
172 int result = 0; // > 0 if for numbers A > B and for text if A < B
174 switch( serverlist_sortbyfield ) {
176 result = A->info.ping - B->info.ping;
178 case SLIF_MAXPLAYERS:
179 result = A->info.maxplayers - B->info.maxplayers;
181 case SLIF_NUMPLAYERS:
182 result = A->info.numplayers - B->info.numplayers;
185 result = A->info.numbots - B->info.numbots;
188 result = A->info.numhumans - B->info.numhumans;
191 result = A->info.freeslots - B->info.freeslots;
194 result = A->info.protocol - B->info.protocol;
197 result = strcmp( B->info.cname, A->info.cname );
200 result = strcasecmp( B->info.game, A->info.game );
203 result = strcasecmp( B->info.map, A->info.map );
206 result = strcasecmp( B->info.mod, A->info.mod );
209 result = strcasecmp( B->info.name, A->info.name );
212 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
215 result = strcasecmp( B->info.players, A->info.qcstatus ); // not really THAT useful, though
218 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
222 if( serverlist_sortdescending )
226 // if the chosen sort key is identical, sort by index
227 // (makes this a stable sort, so that later replies from servers won't
228 // shuffle the servers around when they have the same ping)
232 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
234 // This should actually be done with some intermediate and end-of-function return
246 case SLMO_GREATEREQUAL:
248 case SLMO_NOTCONTAIN:
249 case SLMO_STARTSWITH:
250 case SLMO_NOTSTARTSWITH:
253 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
258 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
261 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
262 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
263 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
264 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
266 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
267 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
270 // Same here, also using an intermediate & final return would be more appropriate
274 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
275 case SLMO_NOTCONTAIN:
276 return !*bufferB || !strstr( bufferA, bufferB );
277 case SLMO_STARTSWITH:
278 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
279 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
280 case SLMO_NOTSTARTSWITH:
281 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
283 return strcmp( bufferA, bufferB ) < 0;
285 return strcmp( bufferA, bufferB ) <= 0;
287 return strcmp( bufferA, bufferB ) == 0;
289 return strcmp( bufferA, bufferB ) > 0;
291 return strcmp( bufferA, bufferB ) != 0;
292 case SLMO_GREATEREQUAL:
293 return strcmp( bufferA, bufferB ) >= 0;
295 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
300 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
302 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
304 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
306 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
308 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
310 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
312 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
314 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
316 if( *mask->info.cname
317 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
320 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
323 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
326 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
329 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
331 if( *mask->info.qcstatus
332 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
334 if( *mask->info.players
335 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
340 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
344 // reject incompatible servers
345 if (entry->info.gameversion != gameversion.integer)
348 // FIXME: change this to be more readable (...)
349 // now check whether it passes through the masks
350 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
351 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
354 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
355 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
357 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
360 if( !serverlist_viewcount ) {
361 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
364 // ok, insert it, we just need to find out where exactly:
367 // check whether to insert it as new first item
368 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
369 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
371 } // check whether to insert it as new last item
372 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
373 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
377 end = serverlist_viewcount - 1;
378 while( end > start + 1 )
380 mid = (start + end) / 2;
381 // test the item that lies in the middle between start and end
382 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
383 // the item has to be in the upper half
386 // the item has to be in the lower half
389 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
392 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
395 for( i = 0; i < serverlist_viewcount; i++ )
397 if (serverlist_viewlist[i] == entry)
399 _ServerList_ViewList_Helper_Remove(i);
405 void ServerList_RebuildViewList(void)
409 serverlist_viewcount = 0;
410 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
411 serverlist_entry_t *entry = &serverlist_cache[i];
412 // also display entries that are currently being refreshed [11/8/2007 Black]
413 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
414 ServerList_ViewList_Insert( entry );
418 void ServerList_ResetMasks(void)
422 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
423 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
424 // numbots needs to be compared to -1 to always succeed
425 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
426 serverlist_andmasks[i].info.numbots = -1;
427 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
428 serverlist_ormasks[i].info.numbots = -1;
431 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
434 int numplayers = 0, maxplayers = 0;
435 for (i = 0;i < serverlist_cachecount;i++)
437 if (serverlist_cache[i].query == SQS_QUERIED)
439 numplayers += serverlist_cache[i].info.numhumans;
440 maxplayers += serverlist_cache[i].info.maxplayers;
443 *numplayerspointer = numplayers;
444 *maxplayerspointer = maxplayers;
448 static void _ServerList_Test(void)
451 for( i = 0 ; i < 1024 ; i++ ) {
452 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
453 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
454 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
455 serverlist_cache[serverlist_cachecount].finished = true;
456 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 );
457 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
458 serverlist_cachecount++;
463 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
465 masterquerytime = realtime;
466 masterquerycount = 0;
467 masterreplycount = 0;
469 serverquerycount = 0;
470 serverreplycount = 0;
471 serverlist_cachecount = 0;
472 serverlist_viewcount = 0;
474 // refresh all entries
476 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
477 serverlist_entry_t *entry = &serverlist_cache[ n ];
478 entry->query = SQS_REFRESHING;
479 entry->querycounter = 0;
482 serverlist_consoleoutput = consoleoutput;
484 //_ServerList_Test();
486 NetConn_QueryMasters(querydp, queryqw);
491 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
493 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
497 if (cl_netpacketloss_receive.integer)
498 for (i = 0;i < cl_numsockets;i++)
499 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
501 if (developer_networking.integer)
503 char addressstring[128], addressstring2[128];
504 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
507 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
508 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
509 Com_HexDumpToConsole((unsigned char *)data, length);
512 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
517 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
521 if (cl_netpacketloss_send.integer)
522 for (i = 0;i < cl_numsockets;i++)
523 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
525 ret = LHNET_Write(mysocket, data, length, peeraddress);
526 if (developer_networking.integer)
528 char addressstring[128], addressstring2[128];
529 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
530 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
531 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
532 Com_HexDumpToConsole((unsigned char *)data, length);
537 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
539 // note this does not include the trailing NULL because we add that in the parser
540 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
543 qboolean NetConn_CanSend(netconn_t *conn)
545 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
546 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
547 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
548 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
549 if (realtime > conn->cleartime)
553 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
558 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
562 // if this packet was supposedly choked, but we find ourselves sending one
563 // anyway, make sure the size counting starts at zero
564 // (this mostly happens on level changes and disconnects and such)
565 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
566 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
568 if (protocol == PROTOCOL_QUAKEWORLD)
571 qboolean sendreliable;
573 // note that it is ok to send empty messages to the qw server,
574 // otherwise it won't respond to us at all
576 sendreliable = false;
577 // if the remote side dropped the last reliable message, resend it
578 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
580 // if the reliable transmit buffer is empty, copy the current message out
581 if (!conn->sendMessageLength && conn->message.cursize)
583 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
584 conn->sendMessageLength = conn->message.cursize;
585 SZ_Clear(&conn->message); // clear the message buffer
586 conn->qw.reliable_sequence ^= 1;
589 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
590 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
591 // last received unreliable packet number, and last received reliable packet number (0 or 1)
592 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
594 conn->outgoing_unreliable_sequence++;
595 // client sends qport in every packet
596 if (conn == cls.netcon)
598 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
600 // also update cls.qw_outgoing_sequence
601 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
603 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
605 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
609 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
611 // add the reliable message if there is one
614 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
615 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
616 packetLen += conn->sendMessageLength;
617 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
620 // add the unreliable message if possible
621 if (packetLen + data->cursize <= 1400)
623 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
624 memcpy(sendbuffer + packetLen, data->data, data->cursize);
625 packetLen += data->cursize;
628 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
631 unreliableMessagesSent++;
633 totallen += packetLen + 28;
637 unsigned int packetLen;
638 unsigned int dataLen;
640 unsigned int *header;
642 // if a reliable message fragment has been lost, send it again
643 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
645 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
647 dataLen = conn->sendMessageLength;
652 dataLen = MAX_PACKETFRAGMENT;
656 packetLen = NET_HEADERSIZE + dataLen;
658 header = (unsigned int *)sendbuffer;
659 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
660 header[1] = BigLong(conn->nq.sendSequence - 1);
661 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
663 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
665 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
667 conn->lastSendTime = realtime;
671 totallen += packetLen + 28;
674 // if we have a new reliable message to send, do so
675 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
677 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
679 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
680 conn->message.overflowed = true;
684 if (developer_networking.integer && conn == cls.netcon)
686 Con_Print("client sending reliable message to server:\n");
687 SZ_HexDumpToConsole(&conn->message);
690 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
691 conn->sendMessageLength = conn->message.cursize;
692 SZ_Clear(&conn->message);
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);
710 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
712 conn->nq.sendSequence++;
714 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
716 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
718 conn->lastSendTime = realtime;
720 reliableMessagesSent++;
722 totallen += packetLen + 28;
725 // if we have an unreliable message to send, do so
728 packetLen = NET_HEADERSIZE + data->cursize;
730 if (packetLen > (int)sizeof(sendbuffer))
732 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
736 header = (unsigned int *)sendbuffer;
737 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
738 header[1] = BigLong(conn->outgoing_unreliable_sequence);
739 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
741 conn->outgoing_unreliable_sequence++;
743 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
745 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
748 unreliableMessagesSent++;
750 totallen += packetLen + 28;
754 // delay later packets to obey rate limit
755 if (conn->cleartime < realtime - 0.1)
756 conn->cleartime = realtime - 0.1;
757 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
758 if (conn->cleartime < realtime)
759 conn->cleartime = realtime;
764 qboolean NetConn_HaveClientPorts(void)
766 return !!cl_numsockets;
769 qboolean NetConn_HaveServerPorts(void)
771 return !!sv_numsockets;
774 void NetConn_CloseClientPorts(void)
776 for (;cl_numsockets > 0;cl_numsockets--)
777 if (cl_sockets[cl_numsockets - 1])
778 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
781 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
783 lhnetaddress_t address;
785 char addressstring2[1024];
786 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
788 if ((s = LHNET_OpenSocket_Connectionless(&address)))
790 cl_sockets[cl_numsockets++] = s;
791 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
792 Con_Printf("Client opened a socket on address %s\n", addressstring2);
796 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
797 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
801 Con_Printf("Client unable to parse address %s\n", addressstring);
804 void NetConn_OpenClientPorts(void)
807 NetConn_CloseClientPorts();
808 port = bound(0, cl_netport.integer, 65535);
809 if (cl_netport.integer != port)
810 Cvar_SetValueQuick(&cl_netport, port);
812 Con_Printf("Client using an automatically assigned port\n");
814 Con_Printf("Client using port %i\n", port);
815 NetConn_OpenClientPort("local:2", 0);
816 NetConn_OpenClientPort(net_address.string, port);
817 //NetConn_OpenClientPort(net_address_ipv6.string, port);
820 void NetConn_CloseServerPorts(void)
822 for (;sv_numsockets > 0;sv_numsockets--)
823 if (sv_sockets[sv_numsockets - 1])
824 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
827 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
829 lhnetaddress_t address;
832 char addressstring2[1024];
834 for (port = defaultport; port <= defaultport + 100; port++)
836 if (LHNETADDRESS_FromString(&address, addressstring, port))
838 if ((s = LHNET_OpenSocket_Connectionless(&address)))
840 sv_sockets[sv_numsockets++] = s;
841 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
842 Con_Printf("Server listening on address %s\n", addressstring2);
847 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
848 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
853 Con_Printf("Server unable to parse address %s\n", addressstring);
854 // if it cant parse one address, it wont be able to parse another for sure
860 void NetConn_OpenServerPorts(int opennetports)
863 NetConn_CloseServerPorts();
864 NetConn_UpdateSockets();
865 port = bound(0, sv_netport.integer, 65535);
868 Con_Printf("Server using port %i\n", port);
869 if (sv_netport.integer != port)
870 Cvar_SetValueQuick(&sv_netport, port);
871 if (cls.state != ca_dedicated)
872 NetConn_OpenServerPort("local:1", 0);
875 NetConn_OpenServerPort(net_address.string, port);
876 //NetConn_OpenServerPort(net_address_ipv6.string, port);
878 if (sv_numsockets == 0)
879 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
882 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
884 int i, a = LHNETADDRESS_GetAddressType(address);
885 for (i = 0;i < cl_numsockets;i++)
886 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
887 return cl_sockets[i];
891 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
893 int i, a = LHNETADDRESS_GetAddressType(address);
894 for (i = 0;i < sv_numsockets;i++)
895 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
896 return sv_sockets[i];
900 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
903 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
904 conn->mysocket = mysocket;
905 conn->peeraddress = *peeraddress;
906 conn->lastMessageTime = realtime;
907 conn->message.data = conn->messagedata;
908 conn->message.maxsize = sizeof(conn->messagedata);
909 conn->message.cursize = 0;
910 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
911 // reduce effectiveness of connection request floods
912 conn->timeout = realtime + net_connecttimeout.value;
913 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
914 conn->next = netconn_list;
919 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
920 void NetConn_Close(netconn_t *conn)
923 // remove connection from list
925 // allow the client to reconnect immediately
926 NetConn_ClearConnectFlood(&(conn->peeraddress));
928 if (conn == netconn_list)
929 netconn_list = conn->next;
932 for (c = netconn_list;c;c = c->next)
936 c->next = conn->next;
940 // not found in list, we'll avoid crashing here...
948 static int clientport = -1;
949 static int clientport2 = -1;
950 static int hostport = -1;
951 void NetConn_UpdateSockets(void)
953 if (cls.state != ca_dedicated)
955 if (clientport2 != cl_netport.integer)
957 clientport2 = cl_netport.integer;
958 if (cls.state == ca_connected)
959 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
961 if (cls.state == ca_disconnected && clientport != clientport2)
963 clientport = clientport2;
964 NetConn_CloseClientPorts();
966 if (cl_numsockets == 0)
967 NetConn_OpenClientPorts();
970 if (hostport != sv_netport.integer)
972 hostport = sv_netport.integer;
974 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
978 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
980 int originallength = length;
984 if (protocol == PROTOCOL_QUAKEWORLD)
986 int sequence, sequence_ack;
987 int reliable_ack, reliable_message;
991 sequence = LittleLong(*((int *)(data + 0)));
992 sequence_ack = LittleLong(*((int *)(data + 4)));
996 if (conn != cls.netcon)
1001 // 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?)
1002 qport = LittleShort(*((int *)(data + 8)));
1008 reliable_message = (sequence >> 31) & 1;
1009 reliable_ack = (sequence_ack >> 31) & 1;
1010 sequence &= ~(1<<31);
1011 sequence_ack &= ~(1<<31);
1012 if (sequence <= conn->qw.incoming_sequence)
1014 //Con_DPrint("Got a stale datagram\n");
1017 count = sequence - (conn->qw.incoming_sequence + 1);
1020 droppedDatagrams += count;
1021 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1024 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1025 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1026 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1027 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1030 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1031 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1032 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1033 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1034 if (reliable_ack == conn->qw.reliable_sequence)
1036 // received, now we will be able to send another reliable message
1037 conn->sendMessageLength = 0;
1038 reliableMessagesReceived++;
1040 conn->qw.incoming_sequence = sequence;
1041 if (conn == cls.netcon)
1042 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1043 conn->qw.incoming_acknowledged = sequence_ack;
1044 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1045 if (reliable_message)
1046 conn->qw.incoming_reliable_sequence ^= 1;
1047 conn->lastMessageTime = realtime;
1048 conn->timeout = realtime + newtimeout;
1049 unreliableMessagesReceived++;
1050 SZ_Clear(&net_message);
1051 SZ_Write(&net_message, data, length);
1059 unsigned int sequence;
1062 qlength = (unsigned int)BigLong(((int *)data)[0]);
1063 flags = qlength & ~NETFLAG_LENGTH_MASK;
1064 qlength &= NETFLAG_LENGTH_MASK;
1065 // control packets were already handled
1066 if (!(flags & NETFLAG_CTL) && qlength == length)
1068 sequence = BigLong(((int *)data)[1]);
1072 if (flags & NETFLAG_UNRELIABLE)
1074 if (sequence >= conn->nq.unreliableReceiveSequence)
1076 if (sequence > conn->nq.unreliableReceiveSequence)
1078 count = sequence - conn->nq.unreliableReceiveSequence;
1079 droppedDatagrams += count;
1080 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1083 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1084 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1085 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1086 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1089 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1090 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1091 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1092 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1093 conn->nq.unreliableReceiveSequence = sequence + 1;
1094 conn->lastMessageTime = realtime;
1095 conn->timeout = realtime + newtimeout;
1096 unreliableMessagesReceived++;
1099 SZ_Clear(&net_message);
1100 SZ_Write(&net_message, data, length);
1106 // Con_DPrint("Got a stale datagram\n");
1109 else if (flags & NETFLAG_ACK)
1111 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1112 if (sequence == (conn->nq.sendSequence - 1))
1114 if (sequence == conn->nq.ackSequence)
1116 conn->nq.ackSequence++;
1117 if (conn->nq.ackSequence != conn->nq.sendSequence)
1118 Con_DPrint("ack sequencing error\n");
1119 conn->lastMessageTime = realtime;
1120 conn->timeout = realtime + newtimeout;
1121 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1123 unsigned int packetLen;
1124 unsigned int dataLen;
1126 unsigned int *header;
1128 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1129 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1131 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1133 dataLen = conn->sendMessageLength;
1138 dataLen = MAX_PACKETFRAGMENT;
1142 packetLen = NET_HEADERSIZE + dataLen;
1144 header = (unsigned int *)sendbuffer;
1145 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1146 header[1] = BigLong(conn->nq.sendSequence);
1147 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1149 conn->nq.sendSequence++;
1151 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1153 conn->lastSendTime = realtime;
1158 conn->sendMessageLength = 0;
1161 // Con_DPrint("Duplicate ACK received\n");
1164 // Con_DPrint("Stale ACK received\n");
1167 else if (flags & NETFLAG_DATA)
1169 unsigned int temppacket[2];
1170 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1171 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1172 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1173 temppacket[1] = BigLong(sequence);
1174 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1175 if (sequence == conn->nq.receiveSequence)
1177 conn->lastMessageTime = realtime;
1178 conn->timeout = realtime + newtimeout;
1179 conn->nq.receiveSequence++;
1180 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1181 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1182 conn->receiveMessageLength += length;
1184 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1185 "Dropping the message!\n", sequence );
1186 conn->receiveMessageLength = 0;
1189 if (flags & NETFLAG_EOM)
1191 reliableMessagesReceived++;
1192 length = conn->receiveMessageLength;
1193 conn->receiveMessageLength = 0;
1196 SZ_Clear(&net_message);
1197 SZ_Write(&net_message, conn->receiveMessage, length);
1204 receivedDuplicateCount++;
1212 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1214 cls.connect_trying = false;
1215 M_Update_Return_Reason("");
1216 // the connection request succeeded, stop current connection and set up a new connection
1218 // if we're connecting to a remote server, shut down any local server
1219 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1220 Host_ShutdownServer ();
1221 // allocate a net connection to keep track of things
1222 cls.netcon = NetConn_Open(mysocket, peeraddress);
1223 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1224 key_dest = key_game;
1226 cls.demonum = -1; // not in the demo loop now
1227 cls.state = ca_connected;
1228 cls.signon = 0; // need all the signon messages before playing
1229 cls.protocol = initialprotocol;
1230 // reset move sequence numbering on this new connection
1231 cls.servermovesequence = 0;
1232 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1233 Cmd_ForwardStringToServer("new");
1234 if (cls.protocol == PROTOCOL_QUAKE)
1236 // write a keepalive (clc_nop) as it seems to greatly improve the
1237 // chances of connecting to a netquake server
1239 unsigned char buf[4];
1240 memset(&msg, 0, sizeof(msg));
1242 msg.maxsize = sizeof(buf);
1243 MSG_WriteChar(&msg, clc_nop);
1244 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1248 int NetConn_IsLocalGame(void)
1250 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1255 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1259 serverlist_entry_t *entry = NULL;
1261 // search the cache for this server and update it
1262 for (n = 0;n < serverlist_cachecount;n++) {
1263 entry = &serverlist_cache[ n ];
1264 if (!strcmp(addressstring, entry->info.cname))
1268 if (n == serverlist_cachecount)
1270 // LAN search doesnt require an answer from the master server so we wont
1271 // know the ping nor will it be initialized already...
1274 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1277 entry = &serverlist_cache[n];
1279 memset(entry, 0, sizeof(*entry));
1280 // store the data the engine cares about (address and ping)
1281 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1282 entry->info.ping = 100000;
1283 entry->querytime = realtime;
1284 // if not in the slist menu we should print the server to console
1285 if (serverlist_consoleoutput)
1286 Con_Printf("querying %s\n", addressstring);
1287 ++serverlist_cachecount;
1289 // if this is the first reply from this server, count it as having replied
1290 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1291 pingtime = bound(0, pingtime, 9999);
1292 if (entry->query == SQS_REFRESHING) {
1293 entry->info.ping = pingtime;
1294 entry->query = SQS_QUERIED;
1296 // convert to unsigned to catch the -1
1297 // 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]
1298 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1302 // other server info is updated by the caller
1306 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1308 serverlist_entry_t *entry = &serverlist_cache[n];
1309 serverlist_info_t *info = &entry->info;
1310 // update description strings for engine menu and console output
1311 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);
1312 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);
1313 if (entry->query == SQS_QUERIED)
1315 if(!serverlist_paused)
1316 ServerList_ViewList_Remove(entry);
1318 // if not in the slist menu we should print the server to console (if wanted)
1319 else if( serverlist_consoleoutput )
1320 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1321 // and finally, update the view set
1322 if(!serverlist_paused)
1323 ServerList_ViewList_Insert( entry );
1324 // update the entry's state
1325 serverlist_cache[n].query = SQS_QUERIED;
1328 // returns true, if it's sensible to continue the processing
1329 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring ) {
1331 serverlist_entry_t *entry;
1333 // ignore the rest of the message if the serverlist is full
1334 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1336 // also ignore it if we have already queried it (other master server response)
1337 for( n = 0 ; n < serverlist_cachecount ; n++ )
1338 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1341 entry = &serverlist_cache[n];
1343 if( n < serverlist_cachecount ) {
1344 // the entry has already been queried once or
1348 memset(entry, 0, sizeof(entry));
1349 entry->protocol = protocol;
1350 // store the data the engine cares about (address and ping)
1351 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1353 // no, then reset the ping right away
1354 entry->info.ping = -1;
1355 // we also want to increase the serverlist_cachecount then
1356 serverlist_cachecount++;
1359 entry->query = SQS_QUERYING;
1364 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1366 qboolean fromserver;
1367 int ret, c, control;
1369 char *string, addressstring2[128], ipstring[32];
1370 char stringbuf[16384];
1372 // quakeworld ingame packet
1373 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1375 // convert the address to a string incase we need it
1376 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1378 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1380 // received a command string - strip off the packaging and put it
1381 // into our string buffer with NULL termination
1384 length = min(length, (int)sizeof(stringbuf) - 1);
1385 memcpy(stringbuf, data, length);
1386 stringbuf[length] = 0;
1389 if (developer_networking.integer)
1391 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1392 Com_HexDumpToConsole(data, length);
1395 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1397 // darkplaces or quake3
1398 char protocolnames[1400];
1399 Protocol_Names(protocolnames, sizeof(protocolnames));
1400 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1401 M_Update_Return_Reason("Got challenge response");
1402 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1403 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1404 // TODO: add userinfo stuff here instead of using NQ commands?
1405 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1408 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1410 // darkplaces or quake3
1411 M_Update_Return_Reason("Accepted");
1412 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1415 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1417 char rejectreason[32];
1418 cls.connect_trying = false;
1420 length = max(length - 7, (int)sizeof(rejectreason) - 1);
1421 memcpy(rejectreason, string, length);
1422 rejectreason[length] = 0;
1423 M_Update_Return_Reason(rejectreason);
1426 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1428 serverlist_info_t *info;
1433 // search the cache for this server and update it
1434 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1438 info = &serverlist_cache[n].info;
1443 info->qcstatus[0] = 0;
1444 info->players[0] = 0;
1445 info->protocol = -1;
1446 info->numplayers = 0;
1448 info->maxplayers = 0;
1449 info->gameversion = 0;
1451 p = strchr(string, '\n');
1454 *p = 0; // cut off the string there
1458 Con_Printf("statusResponse without players block?\n");
1460 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1461 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1462 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1463 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1464 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1465 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1466 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1467 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1468 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1469 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1470 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1471 info->numhumans = info->numplayers - max(0, info->numbots);
1472 info->freeslots = info->maxplayers - info->numplayers;
1474 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1478 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1480 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 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1503 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1504 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1505 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1506 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1507 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1508 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1509 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1510 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1511 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1512 info->numhumans = info->numplayers - max(0, info->numbots);
1513 info->freeslots = info->maxplayers - info->numplayers;
1515 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1519 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1521 // Extract the IP addresses
1525 if (serverlist_consoleoutput)
1526 Con_Print("received DarkPlaces server list...\n");
1527 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1529 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1530 if (serverlist_consoleoutput && developer_networking.integer)
1531 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1533 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring ) ) {
1537 // move on to next address in packet
1541 // begin or resume serverlist queries
1542 serverlist_querysleep = false;
1543 serverlist_querywaittime = realtime + 3;
1546 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1548 // Extract the IP addresses
1552 if (serverlist_consoleoutput)
1553 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1554 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1556 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1557 if (serverlist_consoleoutput && developer_networking.integer)
1558 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1560 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring ) ) {
1564 // move on to next address in packet
1568 // begin or resume serverlist queries
1569 serverlist_querysleep = false;
1570 serverlist_querywaittime = realtime + 3;
1573 if (!strncmp(string, "extResponse ", 12))
1575 ++net_extresponse_count;
1576 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1577 net_extresponse_count = NET_EXTRESPONSE_MAX;
1578 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1579 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1582 if (!strncmp(string, "ping", 4))
1584 if (developer.integer >= 10)
1585 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1586 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1589 if (!strncmp(string, "ack", 3))
1591 // QuakeWorld compatibility
1592 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1594 // challenge message
1595 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1596 M_Update_Return_Reason("Got QuakeWorld challenge response");
1597 cls.qw_qport = qport.integer;
1598 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1599 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1600 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1603 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1606 M_Update_Return_Reason("QuakeWorld Accepted");
1607 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1610 if (length > 2 && !memcmp(string, "n\\", 2))
1612 serverlist_info_t *info;
1616 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1617 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1620 // search the cache for this server and update it
1621 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1625 info = &serverlist_cache[n].info;
1626 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1627 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1628 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1629 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1631 info->numplayers = 0; // updated below
1632 info->numhumans = 0; // updated below
1633 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1634 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1636 // count active players on server
1637 // (we could gather more info, but we're just after the number)
1638 s = strchr(string, '\n');
1642 while (s < string + length)
1644 for (;s < string + length && *s != '\n';s++)
1646 if (s >= string + length)
1654 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1658 if (string[0] == 'n')
1661 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1663 // we may not have liked the packet, but it was a command packet, so
1664 // we're done processing this packet now
1667 // quakeworld ingame packet
1668 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1671 CL_ParseServerMessage();
1674 // netquake control packets, supported for compatibility only
1675 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1678 serverlist_info_t *info;
1682 SZ_Clear(&net_message);
1683 SZ_Write(&net_message, data, length);
1689 if (developer.integer >= 10)
1690 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1691 if (cls.connect_trying)
1693 lhnetaddress_t clientportaddress;
1694 clientportaddress = *peeraddress;
1695 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1696 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1697 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1698 M_Update_Return_Reason("Accepted");
1699 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1703 if (developer.integer >= 10)
1704 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1705 cls.connect_trying = false;
1706 M_Update_Return_Reason((char *)MSG_ReadString());
1708 case CCREP_SERVER_INFO:
1709 if (developer.integer >= 10)
1710 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1711 // LordHavoc: because the quake server may report weird addresses
1712 // we just ignore it and keep the real address
1714 // search the cache for this server and update it
1715 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1719 info = &serverlist_cache[n].info;
1720 strlcpy(info->game, "Quake", sizeof(info->game));
1721 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1722 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1723 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1724 info->numplayers = MSG_ReadByte();
1725 info->maxplayers = MSG_ReadByte();
1726 info->protocol = MSG_ReadByte();
1728 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1731 case CCREP_PLAYER_INFO:
1732 // we got a CCREP_PLAYER_INFO??
1733 //if (developer.integer >= 10)
1734 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1736 case CCREP_RULE_INFO:
1737 // we got a CCREP_RULE_INFO??
1738 //if (developer.integer >= 10)
1739 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1744 SZ_Clear(&net_message);
1745 // we may not have liked the packet, but it was a valid control
1746 // packet, so we're done processing this packet now
1750 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1751 CL_ParseServerMessage();
1755 void NetConn_QueryQueueFrame(void)
1761 static double querycounter = 0;
1763 if(!net_slist_pause.integer && serverlist_paused)
1764 ServerList_RebuildViewList();
1765 serverlist_paused = net_slist_pause.integer;
1767 if (serverlist_querysleep)
1770 // apply a cool down time after master server replies,
1771 // to avoid messing up the ping times on the servers
1772 if (serverlist_querywaittime > realtime)
1775 // each time querycounter reaches 1.0 issue a query
1776 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1777 maxqueries = (int)querycounter;
1778 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1779 querycounter -= maxqueries;
1781 if( maxqueries == 0 ) {
1785 // scan serverlist and issue queries as needed
1786 serverlist_querysleep = true;
1788 timeouttime = realtime - net_slist_timeout.value;
1789 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1791 serverlist_entry_t *entry = &serverlist_cache[ index ];
1792 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1797 serverlist_querysleep = false;
1798 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1803 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1805 lhnetaddress_t address;
1808 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1809 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1811 for (socket = 0; socket < cl_numsockets ; socket++)
1812 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1816 for (socket = 0; socket < cl_numsockets ; socket++)
1817 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1820 // update the entry fields
1821 entry->querytime = realtime;
1822 entry->querycounter++;
1824 // if not in the slist menu we should print the server to console
1825 if (serverlist_consoleoutput)
1826 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1832 // have we tried to refresh this server?
1833 if( entry->query == SQS_REFRESHING ) {
1834 // yes, so update the reply count (since its not responding anymore)
1836 if(!serverlist_paused)
1837 ServerList_ViewList_Remove(entry);
1839 entry->query = SQS_TIMEDOUT;
1844 void NetConn_ClientFrame(void)
1847 lhnetaddress_t peeraddress;
1848 NetConn_UpdateSockets();
1849 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1851 if (cls.connect_remainingtries == 0)
1852 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1853 cls.connect_nextsendtime = realtime + 1;
1854 cls.connect_remainingtries--;
1855 if (cls.connect_remainingtries <= -10)
1857 cls.connect_trying = false;
1858 M_Update_Return_Reason("Connect: Failed");
1861 // try challenge first (newer DP server or QW)
1862 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1863 // then try netquake as a fallback (old server, or netquake)
1864 SZ_Clear(&net_message);
1865 // save space for the header, filled in later
1866 MSG_WriteLong(&net_message, 0);
1867 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1868 MSG_WriteString(&net_message, "QUAKE");
1869 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1870 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1871 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1872 SZ_Clear(&net_message);
1874 for (i = 0;i < cl_numsockets;i++)
1875 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1876 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1877 NetConn_QueryQueueFrame();
1878 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1880 Con_Print("Connection timed out\n");
1882 Host_ShutdownServer ();
1886 #define MAX_CHALLENGES 128
1889 lhnetaddress_t address;
1893 challenge[MAX_CHALLENGES];
1895 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1899 for (i = 0;i < bufferlength - 1;i++)
1903 c = rand () % (127 - 33) + 33;
1904 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1910 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
1911 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1913 const char *qcstatus = NULL;
1914 unsigned int nb_clients = 0, nb_bots = 0, i;
1919 // How many clients are there?
1920 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1922 if (svs.clients[i].active)
1925 if (!svs.clients[i].netconnection)
1930 if(prog->globaloffsets.worldstatus >= 0)
1932 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
1937 qcstatus = p = Mem_Alloc(tempmempool, strlen(str) + 1);
1938 for(q = str; *q; ++q)
1945 // TODO: we should add more information for the full status string
1946 length = dpsnprintf(out_msg, out_size,
1947 "\377\377\377\377%s\x0A"
1948 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1949 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1953 fullstatus ? "statusResponse" : "infoResponse",
1954 gamename, com_modname, gameversion.integer, svs.maxclients,
1955 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1956 qcstatus ? "\\qcstatus\\" : "", qcstatus ? qcstatus : "",
1957 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1958 fullstatus ? "\n" : "");
1962 Mem_Free((char *)qcstatus);
1966 // Make sure it fits in the buffer
1976 savelength = length;
1978 ptr = out_msg + length;
1979 left = (int)out_size - length;
1981 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1983 client_t *cl = &svs.clients[i];
1986 int nameind, cleanind, pingvalue;
1988 char cleanname [sizeof(cl->name)];
1990 // Remove all characters '"' and '\' in the player name
1995 curchar = cl->name[nameind++];
1996 if (curchar != '"' && curchar != '\\')
1998 cleanname[cleanind++] = curchar;
1999 if (cleanind == sizeof(cleanname) - 1)
2002 } while (curchar != '\0');
2004 pingvalue = (int)(cl->ping * 1000.0f);
2005 if(cl->netconnection)
2006 pingvalue = bound(1, pingvalue, 9999);
2010 if(prog->fieldoffsets.clientstatus >= 0)
2012 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2017 qcstatus = p = Mem_Alloc(tempmempool, strlen(str) + 1);
2018 for(q = str; *q; ++q)
2019 if(*q != '\\' && *q != ' ')
2027 length = dpsnprintf(ptr, left, "%s %d \"%s\"\n",
2031 Mem_Free((char *)qcstatus);
2035 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
2043 // turn it into an infoResponse!
2044 out_msg[savelength] = 0;
2045 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2046 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2063 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2065 int floodslotnum, bestfloodslotnum;
2066 double bestfloodtime;
2067 lhnetaddress_t noportpeeraddress;
2068 // see if this is a connect flood
2069 noportpeeraddress = *peeraddress;
2070 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2071 bestfloodslotnum = 0;
2072 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2073 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2075 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2077 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2078 bestfloodslotnum = floodslotnum;
2080 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2082 // this address matches an ongoing flood address
2083 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2085 // renew the ban on this address so it does not expire
2086 // until the flood has subsided
2087 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2088 //Con_Printf("Flood detected!\n");
2091 // the flood appears to have subsided, so allow this
2092 bestfloodslotnum = floodslotnum; // reuse the same slot
2096 // begin a new timeout on this address
2097 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2098 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2099 //Con_Printf("Flood detection initiated!\n");
2103 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2106 lhnetaddress_t noportpeeraddress;
2107 // see if this is a connect flood
2108 noportpeeraddress = *peeraddress;
2109 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2110 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2112 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2114 // this address matches an ongoing flood address
2116 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2117 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2118 //Con_Printf("Flood cleared!\n");
2123 // returns a string describing the user level, or NULL for auth failure
2124 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos)
2129 if(!strcmp(rcon_password.string, password))
2132 if(strcmp(rcon_restricted_password.string, password))
2135 for(text = s; text != endpos; ++text)
2136 if(*text > 0 && (*text < ' ' || *text == ';'))
2137 return NULL; // block possible exploits against the parser/alias expansion
2141 size_t l = strlen(s);
2144 hasquotes = (strchr(s, '"') != NULL);
2145 // sorry, we can't allow these substrings in wildcard expressions,
2146 // as they can mess with the argument counts
2147 text = rcon_restricted_commands.string;
2148 while(COM_ParseToken_Console(&text))
2150 // com_token now contains a pattern to check for...
2151 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2154 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2157 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2159 if(!strcmp(com_token, s))
2162 else // single-arg expression? must match the beginning of the command
2164 if(!strcmp(com_token, s))
2166 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2170 // if we got here, nothing matched!
2177 return "restricted rcon";
2180 extern void SV_SendServerinfo (client_t *client);
2181 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2183 int i, ret, clientnum, best;
2186 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2187 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2192 // convert the address to a string incase we need it
2193 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2195 // see if we can identify the sender as a local player
2196 // (this is necessary for rcon to send a reliable reply if the client is
2197 // actually on the server, not sending remotely)
2198 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2199 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2201 if (i == svs.maxclients)
2204 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2206 // received a command string - strip off the packaging and put it
2207 // into our string buffer with NULL termination
2210 length = min(length, (int)sizeof(stringbuf) - 1);
2211 memcpy(stringbuf, data, length);
2212 stringbuf[length] = 0;
2215 if (developer.integer >= 10)
2217 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2218 Com_HexDumpToConsole(data, length);
2221 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2223 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2225 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2227 if (besttime > challenge[i].time)
2228 besttime = challenge[best = i].time;
2230 // if we did not find an exact match, choose the oldest and
2231 // update address and string
2232 if (i == MAX_CHALLENGES)
2235 challenge[i].address = *peeraddress;
2236 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2238 challenge[i].time = realtime;
2239 // send the challenge
2240 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2243 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2248 if (!(s = SearchInfostring(string, "challenge")))
2250 // validate the challenge
2251 for (i = 0;i < MAX_CHALLENGES;i++)
2252 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2254 // if the challenge is not recognized, drop the packet
2255 if (i == MAX_CHALLENGES)
2258 // check engine protocol
2259 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
2261 if (developer.integer >= 10)
2262 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2263 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2267 // see if this is a duplicate connection request or a disconnected
2268 // client who is rejoining to the same client slot
2269 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2271 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2273 // this is a known client...
2274 if (client->spawned)
2276 // client crashed and is coming back,
2277 // keep their stuff intact
2278 if (developer.integer >= 10)
2279 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2280 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2282 SV_SendServerinfo(client);
2287 // client is still trying to connect,
2288 // so we send a duplicate reply
2289 if (developer.integer >= 10)
2290 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2291 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2297 if (NetConn_PreventConnectFlood(peeraddress))
2300 // find an empty client slot for this new client
2301 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2304 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2306 // allocated connection
2307 if (developer.integer >= 10)
2308 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2309 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2310 // now set up the client
2312 SV_ConnectClient(clientnum, conn);
2314 NetConn_Heartbeat(1);
2319 // no empty slots found - server is full
2320 if (developer.integer >= 10)
2321 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2322 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2326 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2328 const char *challenge = NULL;
2330 // If there was a challenge in the getinfo message
2331 if (length > 8 && string[7] == ' ')
2332 challenge = string + 8;
2334 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2336 if (developer.integer >= 10)
2337 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2338 NetConn_WriteString(mysocket, response, peeraddress);
2342 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2344 const char *challenge = NULL;
2346 // If there was a challenge in the getinfo message
2347 if (length > 10 && string[9] == ' ')
2348 challenge = string + 10;
2350 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2352 if (developer.integer >= 10)
2353 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2354 NetConn_WriteString(mysocket, response, peeraddress);
2358 if (length >= 5 && !memcmp(string, "rcon ", 5))
2361 char *s = string + 5;
2362 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2364 for (i = 0;*s > ' ';s++)
2365 if (i < (int)sizeof(password) - 1)
2367 if(*s <= ' ' && s != endpos) // skip leading ugly space
2370 if (password[0] > ' ')
2372 const char *userlevel = RCon_Authenticate(password, s, endpos);
2375 // looks like a legitimate rcon command with the correct password
2377 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2378 while(s_ptr != endpos)
2380 size_t l = strlen(s_ptr);
2382 Con_Printf(" %s;", s_ptr);
2387 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2388 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2391 size_t l = strlen(s);
2394 client_t *host_client_save = host_client;
2395 Cmd_ExecuteString(s, src_command);
2396 host_client = host_client_save;
2397 // in case it is a command that changes host_client (like restart)
2401 Con_Rcon_Redirect_End();
2405 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2410 if (!strncmp(string, "ping", 4))
2412 if (developer.integer >= 10)
2413 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2414 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2417 if (!strncmp(string, "ack", 3))
2419 // we may not have liked the packet, but it was a command packet, so
2420 // we're done processing this packet now
2423 // netquake control packets, supported for compatibility only, and only
2424 // when running game protocols that are normally served via this connection
2426 // (this protects more modern protocols against being used for
2427 // Quake packet flood Denial Of Service attacks)
2428 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))
2432 const char *protocolname;
2435 SZ_Clear(&net_message);
2436 SZ_Write(&net_message, data, length);
2442 if (developer.integer >= 10)
2443 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2444 if(!islocal && sv_public.integer <= -2)
2447 protocolname = MSG_ReadString();
2448 protocolnumber = MSG_ReadByte();
2449 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2451 if (developer.integer >= 10)
2452 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2453 SZ_Clear(&net_message);
2454 // save space for the header, filled in later
2455 MSG_WriteLong(&net_message, 0);
2456 MSG_WriteByte(&net_message, CCREP_REJECT);
2457 MSG_WriteString(&net_message, "Incompatible version.\n");
2458 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2459 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2460 SZ_Clear(&net_message);
2464 // see if this connect request comes from a known client
2465 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2467 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2469 // this is either a duplicate connection request
2470 // or coming back from a timeout
2471 // (if so, keep their stuff intact)
2474 if (developer.integer >= 10)
2475 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2476 SZ_Clear(&net_message);
2477 // save space for the header, filled in later
2478 MSG_WriteLong(&net_message, 0);
2479 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2480 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2481 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2482 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2483 SZ_Clear(&net_message);
2485 // if client is already spawned, re-send the
2486 // serverinfo message as they'll need it to play
2487 if (client->spawned)
2490 SV_SendServerinfo(client);
2497 // this is a new client, check for connection flood
2498 if (NetConn_PreventConnectFlood(peeraddress))
2501 // find a slot for the new client
2502 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2505 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2507 // connect to the client
2508 // everything is allocated, just fill in the details
2509 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2510 if (developer.integer >= 10)
2511 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2512 // send back the info about the server connection
2513 SZ_Clear(&net_message);
2514 // save space for the header, filled in later
2515 MSG_WriteLong(&net_message, 0);
2516 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2517 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2518 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2519 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2520 SZ_Clear(&net_message);
2521 // now set up the client struct
2523 SV_ConnectClient(clientnum, conn);
2525 NetConn_Heartbeat(1);
2530 if (developer.integer >= 10)
2531 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2532 // no room; try to let player know
2533 SZ_Clear(&net_message);
2534 // save space for the header, filled in later
2535 MSG_WriteLong(&net_message, 0);
2536 MSG_WriteByte(&net_message, CCREP_REJECT);
2537 MSG_WriteString(&net_message, "Server is full.\n");
2538 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2539 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2540 SZ_Clear(&net_message);
2542 case CCREQ_SERVER_INFO:
2543 if (developer.integer >= 10)
2544 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2545 if(!islocal && sv_public.integer <= -1)
2547 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2550 char myaddressstring[128];
2551 if (developer.integer >= 10)
2552 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2553 SZ_Clear(&net_message);
2554 // save space for the header, filled in later
2555 MSG_WriteLong(&net_message, 0);
2556 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2557 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2558 MSG_WriteString(&net_message, myaddressstring);
2559 MSG_WriteString(&net_message, hostname.string);
2560 MSG_WriteString(&net_message, sv.name);
2561 // How many clients are there?
2562 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2563 if (svs.clients[i].active)
2565 MSG_WriteByte(&net_message, numclients);
2566 MSG_WriteByte(&net_message, svs.maxclients);
2567 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2568 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2569 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2570 SZ_Clear(&net_message);
2573 case CCREQ_PLAYER_INFO:
2574 if (developer.integer >= 10)
2575 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2576 if(!islocal && sv_public.integer <= -1)
2580 int playerNumber, activeNumber, clientNumber;
2583 playerNumber = MSG_ReadByte();
2585 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2586 if (client->active && ++activeNumber == playerNumber)
2588 if (clientNumber != svs.maxclients)
2590 SZ_Clear(&net_message);
2591 // save space for the header, filled in later
2592 MSG_WriteLong(&net_message, 0);
2593 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2594 MSG_WriteByte(&net_message, playerNumber);
2595 MSG_WriteString(&net_message, client->name);
2596 MSG_WriteLong(&net_message, client->colors);
2597 MSG_WriteLong(&net_message, client->frags);
2598 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2599 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2600 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2601 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2602 SZ_Clear(&net_message);
2606 case CCREQ_RULE_INFO:
2607 if (developer.integer >= 10)
2608 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2609 if(!islocal && sv_public.integer <= -1)
2616 // find the search start location
2617 prevCvarName = MSG_ReadString();
2618 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2620 // send the response
2621 SZ_Clear(&net_message);
2622 // save space for the header, filled in later
2623 MSG_WriteLong(&net_message, 0);
2624 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2627 MSG_WriteString(&net_message, var->name);
2628 MSG_WriteString(&net_message, var->string);
2630 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2631 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2632 SZ_Clear(&net_message);
2638 SZ_Clear(&net_message);
2639 // we may not have liked the packet, but it was a valid control
2640 // packet, so we're done processing this packet now
2645 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2648 SV_ReadClientMessage();
2656 void NetConn_ServerFrame(void)
2659 lhnetaddress_t peeraddress;
2660 for (i = 0;i < sv_numsockets;i++)
2661 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2662 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2663 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2665 // never timeout loopback connections
2666 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2668 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2670 SV_DropClient(false);
2676 void NetConn_SleepMicroseconds(int microseconds)
2678 LHNET_SleepUntilPacket_Microseconds(microseconds);
2681 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2685 lhnetaddress_t masteraddress;
2686 lhnetaddress_t broadcastaddress;
2689 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2692 // 26000 is the default quake server port, servers on other ports will not
2694 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2695 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2699 for (i = 0;i < cl_numsockets;i++)
2703 // search LAN for Quake servers
2704 SZ_Clear(&net_message);
2705 // save space for the header, filled in later
2706 MSG_WriteLong(&net_message, 0);
2707 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2708 MSG_WriteString(&net_message, "QUAKE");
2709 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2710 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2711 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2712 SZ_Clear(&net_message);
2714 // search LAN for DarkPlaces servers
2715 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2717 // build the getservers message to send to the dpmaster master servers
2718 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2721 for (masternum = 0;sv_masters[masternum].name;masternum++)
2723 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2726 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2733 // only query QuakeWorld servers when the user wants to
2736 for (i = 0;i < cl_numsockets;i++)
2740 // search LAN for QuakeWorld servers
2741 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2743 // build the getservers message to send to the qwmaster master servers
2744 // note this has no -1 prefix, and the trailing nul byte is sent
2745 dpsnprintf(request, sizeof(request), "c\n");
2748 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2750 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2752 if (m_state != m_slist)
2754 char lookupstring[128];
2755 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2756 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2759 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2765 if (!masterquerycount)
2767 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2768 M_Update_Return_Reason("No network");
2772 void NetConn_Heartbeat(int priority)
2774 lhnetaddress_t masteraddress;
2776 lhnetsocket_t *mysocket;
2778 // if it's a state change (client connected), limit next heartbeat to no
2779 // more than 30 sec in the future
2780 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2781 nextheartbeattime = realtime + 30.0;
2783 // limit heartbeatperiod to 30 to 270 second range,
2784 // lower limit is to avoid abusing master servers with excess traffic,
2785 // upper limit is to avoid timing out on the master server (which uses
2787 if (sv_heartbeatperiod.value < 30)
2788 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2789 if (sv_heartbeatperiod.value > 270)
2790 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2792 // make advertising optional and don't advertise singleplayer games, and
2793 // only send a heartbeat as often as the admin wants
2794 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2796 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2797 for (masternum = 0;sv_masters[masternum].name;masternum++)
2798 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2799 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2803 static void Net_Heartbeat_f(void)
2806 NetConn_Heartbeat(2);
2808 Con_Print("No server running, can not heartbeat to master server.\n");
2811 void PrintStats(netconn_t *conn)
2813 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2814 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
2816 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2819 void Net_Stats_f(void)
2822 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2823 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2824 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2825 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2826 Con_Printf("packetsSent = %i\n", packetsSent);
2827 Con_Printf("packetsReSent = %i\n", packetsReSent);
2828 Con_Printf("packetsReceived = %i\n", packetsReceived);
2829 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2830 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2831 Con_Print("connections =\n");
2832 for (conn = netconn_list;conn;conn = conn->next)
2836 void Net_Refresh_f(void)
2838 if (m_state != m_slist) {
2839 Con_Print("Sending new requests to master servers\n");
2840 ServerList_QueryList(false, true, false, true);
2841 Con_Print("Listening for replies...\n");
2843 ServerList_QueryList(false, true, false, false);
2846 void Net_Slist_f(void)
2848 ServerList_ResetMasks();
2849 serverlist_sortbyfield = SLIF_PING;
2850 serverlist_sortdescending = false;
2851 if (m_state != m_slist) {
2852 Con_Print("Sending requests to master servers\n");
2853 ServerList_QueryList(true, true, false, true);
2854 Con_Print("Listening for replies...\n");
2856 ServerList_QueryList(true, true, false, false);
2859 void Net_SlistQW_f(void)
2861 ServerList_ResetMasks();
2862 serverlist_sortbyfield = SLIF_PING;
2863 serverlist_sortdescending = false;
2864 if (m_state != m_slist) {
2865 Con_Print("Sending requests to master servers\n");
2866 ServerList_QueryList(true, false, true, true);
2867 serverlist_consoleoutput = true;
2868 Con_Print("Listening for replies...\n");
2870 ServerList_QueryList(true, false, true, false);
2873 void NetConn_Init(void)
2876 lhnetaddress_t tempaddress;
2877 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2878 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2879 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2880 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2881 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
2882 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2883 Cvar_RegisterVariable(&rcon_restricted_password);
2884 Cvar_RegisterVariable(&rcon_restricted_commands);
2885 Cvar_RegisterVariable(&net_slist_queriespersecond);
2886 Cvar_RegisterVariable(&net_slist_queriesperframe);
2887 Cvar_RegisterVariable(&net_slist_timeout);
2888 Cvar_RegisterVariable(&net_slist_maxtries);
2889 Cvar_RegisterVariable(&net_slist_pause);
2890 Cvar_RegisterVariable(&net_messagetimeout);
2891 Cvar_RegisterVariable(&net_connecttimeout);
2892 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2893 Cvar_RegisterVariable(&cl_netlocalping);
2894 Cvar_RegisterVariable(&cl_netpacketloss_send);
2895 Cvar_RegisterVariable(&cl_netpacketloss_receive);
2896 Cvar_RegisterVariable(&hostname);
2897 Cvar_RegisterVariable(&developer_networking);
2898 Cvar_RegisterVariable(&cl_netport);
2899 Cvar_RegisterVariable(&sv_netport);
2900 Cvar_RegisterVariable(&net_address);
2901 //Cvar_RegisterVariable(&net_address_ipv6);
2902 Cvar_RegisterVariable(&sv_public);
2903 Cvar_RegisterVariable(&sv_heartbeatperiod);
2904 for (i = 0;sv_masters[i].name;i++)
2905 Cvar_RegisterVariable(&sv_masters[i]);
2906 Cvar_RegisterVariable(&gameversion);
2907 // 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.
2908 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2910 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2912 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
2913 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2916 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2918 // 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
2919 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2921 i = atoi(com_argv[i + 1]);
2922 if (i >= 0 && i < 65536)
2924 Con_Printf("-port option used, setting port cvar to %i\n", i);
2925 Cvar_SetValueQuick(&sv_netport, i);
2928 Con_Printf("-port option used, but %i is not a valid port number\n", i);
2932 net_message.data = net_message_buf;
2933 net_message.maxsize = sizeof(net_message_buf);
2934 net_message.cursize = 0;
2938 void NetConn_Shutdown(void)
2940 NetConn_CloseClientPorts();
2941 NetConn_CloseServerPorts();