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", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40 {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
41 {0, "sv_masterextra3", "92.62.40.6", "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","15", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods). Must be above 10 seconds."};
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)"};
78 static cvar_t net_slist_favorites = {CVAR_SAVE, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
80 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"};
81 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode"};
82 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
84 /* statistic counters */
85 static int packetsSent = 0;
86 static int packetsReSent = 0;
87 static int packetsReceived = 0;
88 static int receivedDuplicateCount = 0;
89 static int droppedDatagrams = 0;
91 static int unreliableMessagesSent = 0;
92 static int unreliableMessagesReceived = 0;
93 static int reliableMessagesSent = 0;
94 static int reliableMessagesReceived = 0;
96 double masterquerytime = -1000;
97 int masterquerycount = 0;
98 int masterreplycount = 0;
99 int serverquerycount = 0;
100 int serverreplycount = 0;
102 // this is only false if there are still servers left to query
103 static qboolean serverlist_querysleep = true;
104 static qboolean serverlist_paused = false;
105 // this is pushed a second or two ahead of realtime whenever a master server
106 // reply is received, to avoid issuing queries while master replies are still
107 // flooding in (which would make a mess of the ping times)
108 static double serverlist_querywaittime = 0;
110 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
111 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
113 static int cl_numsockets;
114 static lhnetsocket_t *cl_sockets[16];
115 static int sv_numsockets;
116 static lhnetsocket_t *sv_sockets[16];
118 netconn_t *netconn_list = NULL;
119 mempool_t *netconn_mempool = NULL;
121 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
122 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
123 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
124 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
126 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
127 int net_extresponse_count = 0;
128 int net_extresponse_last = 0;
130 // ServerList interface
131 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
132 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
134 serverlist_infofield_t serverlist_sortbyfield;
135 int serverlist_sortflags;
137 int serverlist_viewcount = 0;
138 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
140 int serverlist_cachecount;
141 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
143 qboolean serverlist_consoleoutput;
145 // helper function to insert a value into the viewset
146 // spare entries will be removed
147 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
150 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
151 i = serverlist_viewcount++;
153 i = SERVERLIST_VIEWLISTSIZE - 1;
156 for( ; i > index ; i-- )
157 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
159 serverlist_viewlist[index] = entry;
162 // we suppose serverlist_viewcount to be valid, ie > 0
163 static void _ServerList_ViewList_Helper_Remove( int index )
165 serverlist_viewcount--;
166 for( ; index < serverlist_viewcount ; index++ )
167 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
170 // returns true if A should be inserted before B
171 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
173 int result = 0; // > 0 if for numbers A > B and for text if A < B
175 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
177 if(A->info.isfavorite != B->info.isfavorite)
178 return A->info.isfavorite;
181 switch( serverlist_sortbyfield ) {
183 result = A->info.ping - B->info.ping;
185 case SLIF_MAXPLAYERS:
186 result = A->info.maxplayers - B->info.maxplayers;
188 case SLIF_NUMPLAYERS:
189 result = A->info.numplayers - B->info.numplayers;
192 result = A->info.numbots - B->info.numbots;
195 result = A->info.numhumans - B->info.numhumans;
198 result = A->info.freeslots - B->info.freeslots;
201 result = A->info.protocol - B->info.protocol;
204 result = strcmp( B->info.cname, A->info.cname );
207 result = strcasecmp( B->info.game, A->info.game );
210 result = strcasecmp( B->info.map, A->info.map );
213 result = strcasecmp( B->info.mod, A->info.mod );
216 result = strcasecmp( B->info.name, A->info.name );
219 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
221 case SLIF_ISFAVORITE:
222 result = !!B->info.isfavorite - !!A->info.isfavorite;
225 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
231 if( serverlist_sortflags & SLSF_DESCENDING )
237 // if the chosen sort key is identical, sort by index
238 // (makes this a stable sort, so that later replies from servers won't
239 // shuffle the servers around when they have the same ping)
243 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
245 // This should actually be done with some intermediate and end-of-function return
257 case SLMO_GREATEREQUAL:
259 case SLMO_NOTCONTAIN:
260 case SLMO_STARTSWITH:
261 case SLMO_NOTSTARTSWITH:
264 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
269 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
272 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
273 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
274 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
275 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
277 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
278 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
281 // Same here, also using an intermediate & final return would be more appropriate
285 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
286 case SLMO_NOTCONTAIN:
287 return !*bufferB || !strstr( bufferA, bufferB );
288 case SLMO_STARTSWITH:
289 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
290 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
291 case SLMO_NOTSTARTSWITH:
292 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
294 return strcmp( bufferA, bufferB ) < 0;
296 return strcmp( bufferA, bufferB ) <= 0;
298 return strcmp( bufferA, bufferB ) == 0;
300 return strcmp( bufferA, bufferB ) > 0;
302 return strcmp( bufferA, bufferB ) != 0;
303 case SLMO_GREATEREQUAL:
304 return strcmp( bufferA, bufferB ) >= 0;
306 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
311 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
313 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
315 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
317 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
319 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
321 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
323 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
325 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
327 if( *mask->info.cname
328 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
331 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
334 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
337 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
340 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
342 if( *mask->info.qcstatus
343 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
345 if( *mask->info.players
346 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
348 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
353 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
358 // reject incompatible servers
359 if (entry->info.gameversion != gameversion.integer)
362 // refresh the "favorite" status
363 text = net_slist_favorites.string;
364 entry->info.isfavorite = false;
365 while(COM_ParseToken_Console(&text))
367 if(!strcmp(com_token, entry->info.cname))
369 entry->info.isfavorite = true;
374 // FIXME: change this to be more readable (...)
375 // now check whether it passes through the masks
376 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
377 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
380 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
381 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
383 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
386 if( !serverlist_viewcount ) {
387 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
390 // ok, insert it, we just need to find out where exactly:
393 // check whether to insert it as new first item
394 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
395 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
397 } // check whether to insert it as new last item
398 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
399 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
403 end = serverlist_viewcount - 1;
404 while( end > start + 1 )
406 mid = (start + end) / 2;
407 // test the item that lies in the middle between start and end
408 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
409 // the item has to be in the upper half
412 // the item has to be in the lower half
415 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
418 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
421 for( i = 0; i < serverlist_viewcount; i++ )
423 if (serverlist_viewlist[i] == entry)
425 _ServerList_ViewList_Helper_Remove(i);
431 void ServerList_RebuildViewList(void)
435 serverlist_viewcount = 0;
436 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
437 serverlist_entry_t *entry = &serverlist_cache[i];
438 // also display entries that are currently being refreshed [11/8/2007 Black]
439 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
440 ServerList_ViewList_Insert( entry );
444 void ServerList_ResetMasks(void)
448 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
449 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
450 // numbots needs to be compared to -1 to always succeed
451 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
452 serverlist_andmasks[i].info.numbots = -1;
453 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
454 serverlist_ormasks[i].info.numbots = -1;
457 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
460 int numplayers = 0, maxplayers = 0;
461 for (i = 0;i < serverlist_cachecount;i++)
463 if (serverlist_cache[i].query == SQS_QUERIED)
465 numplayers += serverlist_cache[i].info.numhumans;
466 maxplayers += serverlist_cache[i].info.maxplayers;
469 *numplayerspointer = numplayers;
470 *maxplayerspointer = maxplayers;
474 static void _ServerList_Test(void)
477 for( i = 0 ; i < 1024 ; i++ ) {
478 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
479 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
480 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
481 serverlist_cache[serverlist_cachecount].finished = true;
482 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 );
483 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
484 serverlist_cachecount++;
489 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
491 masterquerytime = realtime;
492 masterquerycount = 0;
493 masterreplycount = 0;
495 serverquerycount = 0;
496 serverreplycount = 0;
497 serverlist_cachecount = 0;
498 serverlist_viewcount = 0;
500 // refresh all entries
502 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
503 serverlist_entry_t *entry = &serverlist_cache[ n ];
504 entry->query = SQS_REFRESHING;
505 entry->querycounter = 0;
508 serverlist_consoleoutput = consoleoutput;
510 //_ServerList_Test();
512 NetConn_QueryMasters(querydp, queryqw);
517 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
519 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
523 if (cl_netpacketloss_receive.integer)
524 for (i = 0;i < cl_numsockets;i++)
525 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
527 if (developer_networking.integer)
529 char addressstring[128], addressstring2[128];
530 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
533 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
534 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
535 Com_HexDumpToConsole((unsigned char *)data, length);
538 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
543 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
547 if (cl_netpacketloss_send.integer)
548 for (i = 0;i < cl_numsockets;i++)
549 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
551 ret = LHNET_Write(mysocket, data, length, peeraddress);
552 if (developer_networking.integer)
554 char addressstring[128], addressstring2[128];
555 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
556 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
557 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
558 Com_HexDumpToConsole((unsigned char *)data, length);
563 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
565 // note this does not include the trailing NULL because we add that in the parser
566 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
569 qboolean NetConn_CanSend(netconn_t *conn)
571 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
572 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
573 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
574 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
575 if (realtime > conn->cleartime)
579 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
584 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
588 // if this packet was supposedly choked, but we find ourselves sending one
589 // anyway, make sure the size counting starts at zero
590 // (this mostly happens on level changes and disconnects and such)
591 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
592 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
594 if (protocol == PROTOCOL_QUAKEWORLD)
597 qboolean sendreliable;
599 // note that it is ok to send empty messages to the qw server,
600 // otherwise it won't respond to us at all
602 sendreliable = false;
603 // if the remote side dropped the last reliable message, resend it
604 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
606 // if the reliable transmit buffer is empty, copy the current message out
607 if (!conn->sendMessageLength && conn->message.cursize)
609 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
610 conn->sendMessageLength = conn->message.cursize;
611 SZ_Clear(&conn->message); // clear the message buffer
612 conn->qw.reliable_sequence ^= 1;
615 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
616 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
617 // last received unreliable packet number, and last received reliable packet number (0 or 1)
618 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
620 conn->outgoing_unreliable_sequence++;
621 // client sends qport in every packet
622 if (conn == cls.netcon)
624 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
626 // also update cls.qw_outgoing_sequence
627 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
629 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
631 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
635 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
637 // add the reliable message if there is one
640 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
641 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
642 packetLen += conn->sendMessageLength;
643 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
646 // add the unreliable message if possible
647 if (packetLen + data->cursize <= 1400)
649 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
650 memcpy(sendbuffer + packetLen, data->data, data->cursize);
651 packetLen += data->cursize;
654 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
657 unreliableMessagesSent++;
659 totallen += packetLen + 28;
663 unsigned int packetLen;
664 unsigned int dataLen;
666 unsigned int *header;
668 // if a reliable message fragment has been lost, send it again
669 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
671 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
673 dataLen = conn->sendMessageLength;
678 dataLen = MAX_PACKETFRAGMENT;
682 packetLen = NET_HEADERSIZE + dataLen;
684 header = (unsigned int *)sendbuffer;
685 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
686 header[1] = BigLong(conn->nq.sendSequence - 1);
687 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
689 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
691 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
693 conn->lastSendTime = realtime;
697 totallen += packetLen + 28;
700 // if we have a new reliable message to send, do so
701 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
703 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
705 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
706 conn->message.overflowed = true;
710 if (developer_networking.integer && conn == cls.netcon)
712 Con_Print("client sending reliable message to server:\n");
713 SZ_HexDumpToConsole(&conn->message);
716 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
717 conn->sendMessageLength = conn->message.cursize;
718 SZ_Clear(&conn->message);
720 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
722 dataLen = conn->sendMessageLength;
727 dataLen = MAX_PACKETFRAGMENT;
731 packetLen = NET_HEADERSIZE + dataLen;
733 header = (unsigned int *)sendbuffer;
734 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
735 header[1] = BigLong(conn->nq.sendSequence);
736 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
738 conn->nq.sendSequence++;
740 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
742 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
744 conn->lastSendTime = realtime;
746 reliableMessagesSent++;
748 totallen += packetLen + 28;
751 // if we have an unreliable message to send, do so
754 packetLen = NET_HEADERSIZE + data->cursize;
756 if (packetLen > (int)sizeof(sendbuffer))
758 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
762 header = (unsigned int *)sendbuffer;
763 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
764 header[1] = BigLong(conn->outgoing_unreliable_sequence);
765 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
767 conn->outgoing_unreliable_sequence++;
769 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
771 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
774 unreliableMessagesSent++;
776 totallen += packetLen + 28;
780 // delay later packets to obey rate limit
781 if (conn->cleartime < realtime - 0.1)
782 conn->cleartime = realtime - 0.1;
783 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
784 if (conn->cleartime < realtime)
785 conn->cleartime = realtime;
790 qboolean NetConn_HaveClientPorts(void)
792 return !!cl_numsockets;
795 qboolean NetConn_HaveServerPorts(void)
797 return !!sv_numsockets;
800 void NetConn_CloseClientPorts(void)
802 for (;cl_numsockets > 0;cl_numsockets--)
803 if (cl_sockets[cl_numsockets - 1])
804 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
807 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
809 lhnetaddress_t address;
811 char addressstring2[1024];
812 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
814 if ((s = LHNET_OpenSocket_Connectionless(&address)))
816 cl_sockets[cl_numsockets++] = s;
817 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
818 Con_Printf("Client opened a socket on address %s\n", addressstring2);
822 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
823 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
827 Con_Printf("Client unable to parse address %s\n", addressstring);
830 void NetConn_OpenClientPorts(void)
833 NetConn_CloseClientPorts();
834 port = bound(0, cl_netport.integer, 65535);
835 if (cl_netport.integer != port)
836 Cvar_SetValueQuick(&cl_netport, port);
838 Con_Printf("Client using an automatically assigned port\n");
840 Con_Printf("Client using port %i\n", port);
841 NetConn_OpenClientPort("local:2", 0);
842 NetConn_OpenClientPort(net_address.string, port);
843 //NetConn_OpenClientPort(net_address_ipv6.string, port);
846 void NetConn_CloseServerPorts(void)
848 for (;sv_numsockets > 0;sv_numsockets--)
849 if (sv_sockets[sv_numsockets - 1])
850 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
853 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
855 lhnetaddress_t address;
858 char addressstring2[1024];
860 for (port = defaultport; port <= defaultport + 100; port++)
862 if (LHNETADDRESS_FromString(&address, addressstring, port))
864 if ((s = LHNET_OpenSocket_Connectionless(&address)))
866 sv_sockets[sv_numsockets++] = s;
867 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
868 Con_Printf("Server listening on address %s\n", addressstring2);
873 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
874 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
879 Con_Printf("Server unable to parse address %s\n", addressstring);
880 // if it cant parse one address, it wont be able to parse another for sure
886 void NetConn_OpenServerPorts(int opennetports)
889 NetConn_CloseServerPorts();
890 NetConn_UpdateSockets();
891 port = bound(0, sv_netport.integer, 65535);
894 Con_Printf("Server using port %i\n", port);
895 if (sv_netport.integer != port)
896 Cvar_SetValueQuick(&sv_netport, port);
897 if (cls.state != ca_dedicated)
898 NetConn_OpenServerPort("local:1", 0);
901 NetConn_OpenServerPort(net_address.string, port);
902 //NetConn_OpenServerPort(net_address_ipv6.string, port);
904 if (sv_numsockets == 0)
905 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
908 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
910 int i, a = LHNETADDRESS_GetAddressType(address);
911 for (i = 0;i < cl_numsockets;i++)
912 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
913 return cl_sockets[i];
917 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
919 int i, a = LHNETADDRESS_GetAddressType(address);
920 for (i = 0;i < sv_numsockets;i++)
921 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
922 return sv_sockets[i];
926 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
929 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
930 conn->mysocket = mysocket;
931 conn->peeraddress = *peeraddress;
932 conn->lastMessageTime = realtime;
933 conn->message.data = conn->messagedata;
934 conn->message.maxsize = sizeof(conn->messagedata);
935 conn->message.cursize = 0;
936 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
937 // reduce effectiveness of connection request floods
938 conn->timeout = realtime + net_connecttimeout.value;
939 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
940 conn->next = netconn_list;
945 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
946 void NetConn_Close(netconn_t *conn)
949 // remove connection from list
951 // allow the client to reconnect immediately
952 NetConn_ClearConnectFlood(&(conn->peeraddress));
954 if (conn == netconn_list)
955 netconn_list = conn->next;
958 for (c = netconn_list;c;c = c->next)
962 c->next = conn->next;
966 // not found in list, we'll avoid crashing here...
974 static int clientport = -1;
975 static int clientport2 = -1;
976 static int hostport = -1;
977 void NetConn_UpdateSockets(void)
979 if (cls.state != ca_dedicated)
981 if (clientport2 != cl_netport.integer)
983 clientport2 = cl_netport.integer;
984 if (cls.state == ca_connected)
985 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
987 if (cls.state == ca_disconnected && clientport != clientport2)
989 clientport = clientport2;
990 NetConn_CloseClientPorts();
992 if (cl_numsockets == 0)
993 NetConn_OpenClientPorts();
996 if (hostport != sv_netport.integer)
998 hostport = sv_netport.integer;
1000 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1004 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1006 int originallength = length;
1010 if (protocol == PROTOCOL_QUAKEWORLD)
1012 int sequence, sequence_ack;
1013 int reliable_ack, reliable_message;
1017 sequence = LittleLong(*((int *)(data + 0)));
1018 sequence_ack = LittleLong(*((int *)(data + 4)));
1022 if (conn != cls.netcon)
1027 // 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?)
1028 qport = LittleShort(*((int *)(data + 8)));
1034 reliable_message = (sequence >> 31) & 1;
1035 reliable_ack = (sequence_ack >> 31) & 1;
1036 sequence &= ~(1<<31);
1037 sequence_ack &= ~(1<<31);
1038 if (sequence <= conn->qw.incoming_sequence)
1040 //Con_DPrint("Got a stale datagram\n");
1043 count = sequence - (conn->qw.incoming_sequence + 1);
1046 droppedDatagrams += count;
1047 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1050 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1051 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1052 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1053 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1056 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1057 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1058 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1059 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1060 if (reliable_ack == conn->qw.reliable_sequence)
1062 // received, now we will be able to send another reliable message
1063 conn->sendMessageLength = 0;
1064 reliableMessagesReceived++;
1066 conn->qw.incoming_sequence = sequence;
1067 if (conn == cls.netcon)
1068 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1069 conn->qw.incoming_acknowledged = sequence_ack;
1070 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1071 if (reliable_message)
1072 conn->qw.incoming_reliable_sequence ^= 1;
1073 conn->lastMessageTime = realtime;
1074 conn->timeout = realtime + newtimeout;
1075 unreliableMessagesReceived++;
1076 SZ_Clear(&net_message);
1077 SZ_Write(&net_message, data, length);
1085 unsigned int sequence;
1088 qlength = (unsigned int)BigLong(((int *)data)[0]);
1089 flags = qlength & ~NETFLAG_LENGTH_MASK;
1090 qlength &= NETFLAG_LENGTH_MASK;
1091 // control packets were already handled
1092 if (!(flags & NETFLAG_CTL) && qlength == length)
1094 sequence = BigLong(((int *)data)[1]);
1098 if (flags & NETFLAG_UNRELIABLE)
1100 if (sequence >= conn->nq.unreliableReceiveSequence)
1102 if (sequence > conn->nq.unreliableReceiveSequence)
1104 count = sequence - conn->nq.unreliableReceiveSequence;
1105 droppedDatagrams += count;
1106 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1109 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1110 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1111 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1112 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1115 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1116 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1117 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1118 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1119 conn->nq.unreliableReceiveSequence = sequence + 1;
1120 conn->lastMessageTime = realtime;
1121 conn->timeout = realtime + newtimeout;
1122 unreliableMessagesReceived++;
1125 SZ_Clear(&net_message);
1126 SZ_Write(&net_message, data, length);
1132 // Con_DPrint("Got a stale datagram\n");
1135 else if (flags & NETFLAG_ACK)
1137 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1138 if (sequence == (conn->nq.sendSequence - 1))
1140 if (sequence == conn->nq.ackSequence)
1142 conn->nq.ackSequence++;
1143 if (conn->nq.ackSequence != conn->nq.sendSequence)
1144 Con_DPrint("ack sequencing error\n");
1145 conn->lastMessageTime = realtime;
1146 conn->timeout = realtime + newtimeout;
1147 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1149 unsigned int packetLen;
1150 unsigned int dataLen;
1152 unsigned int *header;
1154 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1155 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1157 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1159 dataLen = conn->sendMessageLength;
1164 dataLen = MAX_PACKETFRAGMENT;
1168 packetLen = NET_HEADERSIZE + dataLen;
1170 header = (unsigned int *)sendbuffer;
1171 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1172 header[1] = BigLong(conn->nq.sendSequence);
1173 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1175 conn->nq.sendSequence++;
1177 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1179 conn->lastSendTime = realtime;
1184 conn->sendMessageLength = 0;
1187 // Con_DPrint("Duplicate ACK received\n");
1190 // Con_DPrint("Stale ACK received\n");
1193 else if (flags & NETFLAG_DATA)
1195 unsigned int temppacket[2];
1196 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1197 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1198 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1199 temppacket[1] = BigLong(sequence);
1200 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1201 if (sequence == conn->nq.receiveSequence)
1203 conn->lastMessageTime = realtime;
1204 conn->timeout = realtime + newtimeout;
1205 conn->nq.receiveSequence++;
1206 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1207 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1208 conn->receiveMessageLength += length;
1210 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1211 "Dropping the message!\n", sequence );
1212 conn->receiveMessageLength = 0;
1215 if (flags & NETFLAG_EOM)
1217 reliableMessagesReceived++;
1218 length = conn->receiveMessageLength;
1219 conn->receiveMessageLength = 0;
1222 SZ_Clear(&net_message);
1223 SZ_Write(&net_message, conn->receiveMessage, length);
1230 receivedDuplicateCount++;
1238 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1240 cls.connect_trying = false;
1241 M_Update_Return_Reason("");
1242 // the connection request succeeded, stop current connection and set up a new connection
1244 // if we're connecting to a remote server, shut down any local server
1245 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1246 Host_ShutdownServer ();
1247 // allocate a net connection to keep track of things
1248 cls.netcon = NetConn_Open(mysocket, peeraddress);
1249 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1250 key_dest = key_game;
1252 cls.demonum = -1; // not in the demo loop now
1253 cls.state = ca_connected;
1254 cls.signon = 0; // need all the signon messages before playing
1255 cls.protocol = initialprotocol;
1256 // reset move sequence numbering on this new connection
1257 cls.servermovesequence = 0;
1258 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1259 Cmd_ForwardStringToServer("new");
1260 if (cls.protocol == PROTOCOL_QUAKE)
1262 // write a keepalive (clc_nop) as it seems to greatly improve the
1263 // chances of connecting to a netquake server
1265 unsigned char buf[4];
1266 memset(&msg, 0, sizeof(msg));
1268 msg.maxsize = sizeof(buf);
1269 MSG_WriteChar(&msg, clc_nop);
1270 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1274 int NetConn_IsLocalGame(void)
1276 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1281 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1285 serverlist_entry_t *entry = NULL;
1287 // search the cache for this server and update it
1288 for (n = 0;n < serverlist_cachecount;n++) {
1289 entry = &serverlist_cache[ n ];
1290 if (!strcmp(addressstring, entry->info.cname))
1294 if (n == serverlist_cachecount)
1296 // LAN search doesnt require an answer from the master server so we wont
1297 // know the ping nor will it be initialized already...
1300 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1303 entry = &serverlist_cache[n];
1305 memset(entry, 0, sizeof(*entry));
1306 // store the data the engine cares about (address and ping)
1307 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1308 entry->info.ping = 100000;
1309 entry->querytime = realtime;
1310 // if not in the slist menu we should print the server to console
1311 if (serverlist_consoleoutput)
1312 Con_Printf("querying %s\n", addressstring);
1313 ++serverlist_cachecount;
1316 // we should not NEED this part...
1317 text = net_slist_favorites.string;
1318 while(COM_ParseToken_Console(&text))
1320 if(!strcmp(com_token, addressstring))
1321 entry->isfavorite = 1;
1325 // if this is the first reply from this server, count it as having replied
1326 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1327 pingtime = bound(0, pingtime, 9999);
1328 if (entry->query == SQS_REFRESHING) {
1329 entry->info.ping = pingtime;
1330 entry->query = SQS_QUERIED;
1332 // convert to unsigned to catch the -1
1333 // 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]
1334 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1338 // other server info is updated by the caller
1342 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1344 serverlist_entry_t *entry = &serverlist_cache[n];
1345 serverlist_info_t *info = &entry->info;
1346 // update description strings for engine menu and console output
1347 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);
1348 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);
1349 if (entry->query == SQS_QUERIED)
1351 if(!serverlist_paused)
1352 ServerList_ViewList_Remove(entry);
1354 // if not in the slist menu we should print the server to console (if wanted)
1355 else if( serverlist_consoleoutput )
1356 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1357 // and finally, update the view set
1358 if(!serverlist_paused)
1359 ServerList_ViewList_Insert( entry );
1360 // update the entry's state
1361 serverlist_cache[n].query = SQS_QUERIED;
1364 // returns true, if it's sensible to continue the processing
1365 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1367 serverlist_entry_t *entry;
1369 // ignore the rest of the message if the serverlist is full
1370 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1372 // also ignore it if we have already queried it (other master server response)
1373 for( n = 0 ; n < serverlist_cachecount ; n++ )
1374 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1377 entry = &serverlist_cache[n];
1379 if( n < serverlist_cachecount ) {
1380 // the entry has already been queried once or
1384 memset(entry, 0, sizeof(entry));
1385 entry->protocol = protocol;
1386 // store the data the engine cares about (address and ping)
1387 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1389 entry->info.isfavorite = isfavorite;
1391 // no, then reset the ping right away
1392 entry->info.ping = -1;
1393 // we also want to increase the serverlist_cachecount then
1394 serverlist_cachecount++;
1397 entry->query = SQS_QUERYING;
1402 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1404 qboolean fromserver;
1405 int ret, c, control;
1407 char *string, addressstring2[128], ipstring[32];
1408 char stringbuf[16384];
1410 // quakeworld ingame packet
1411 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1413 // convert the address to a string incase we need it
1414 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1416 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1418 // received a command string - strip off the packaging and put it
1419 // into our string buffer with NULL termination
1422 length = min(length, (int)sizeof(stringbuf) - 1);
1423 memcpy(stringbuf, data, length);
1424 stringbuf[length] = 0;
1427 if (developer_networking.integer)
1429 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1430 Com_HexDumpToConsole(data, length);
1433 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1435 // darkplaces or quake3
1436 char protocolnames[1400];
1437 Protocol_Names(protocolnames, sizeof(protocolnames));
1438 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1439 M_Update_Return_Reason("Got challenge response");
1440 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1441 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1442 // TODO: add userinfo stuff here instead of using NQ commands?
1443 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1446 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1448 // darkplaces or quake3
1449 M_Update_Return_Reason("Accepted");
1450 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1453 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1455 char rejectreason[32];
1456 cls.connect_trying = false;
1458 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1459 memcpy(rejectreason, string, length);
1460 rejectreason[length] = 0;
1461 M_Update_Return_Reason(rejectreason);
1464 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1466 serverlist_info_t *info;
1471 // search the cache for this server and update it
1472 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1476 info = &serverlist_cache[n].info;
1481 info->qcstatus[0] = 0;
1482 info->players[0] = 0;
1483 info->protocol = -1;
1484 info->numplayers = 0;
1486 info->maxplayers = 0;
1487 info->gameversion = 0;
1489 p = strchr(string, '\n');
1492 *p = 0; // cut off the string there
1496 Con_Printf("statusResponse without players block?\n");
1498 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1499 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1500 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1501 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1502 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1503 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1504 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1505 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1506 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1507 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1508 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1509 info->numhumans = info->numplayers - max(0, info->numbots);
1510 info->freeslots = info->maxplayers - info->numplayers;
1512 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1516 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1518 serverlist_info_t *info;
1522 // search the cache for this server and update it
1523 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1527 info = &serverlist_cache[n].info;
1532 info->qcstatus[0] = 0;
1533 info->players[0] = 0;
1534 info->protocol = -1;
1535 info->numplayers = 0;
1537 info->maxplayers = 0;
1538 info->gameversion = 0;
1540 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1541 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1542 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1543 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1544 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1545 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1546 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1547 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1548 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1549 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1550 info->numhumans = info->numplayers - max(0, info->numbots);
1551 info->freeslots = info->maxplayers - info->numplayers;
1553 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1557 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1559 // Extract the IP addresses
1563 if (serverlist_consoleoutput)
1564 Con_Print("received DarkPlaces server list...\n");
1565 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1567 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1568 if (serverlist_consoleoutput && developer_networking.integer)
1569 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1571 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1575 // move on to next address in packet
1579 // begin or resume serverlist queries
1580 serverlist_querysleep = false;
1581 serverlist_querywaittime = realtime + 3;
1584 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1586 // Extract the IP addresses
1590 if (serverlist_consoleoutput)
1591 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1592 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1594 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1595 if (serverlist_consoleoutput && developer_networking.integer)
1596 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1598 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1602 // move on to next address in packet
1606 // begin or resume serverlist queries
1607 serverlist_querysleep = false;
1608 serverlist_querywaittime = realtime + 3;
1611 if (!strncmp(string, "extResponse ", 12))
1613 ++net_extresponse_count;
1614 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1615 net_extresponse_count = NET_EXTRESPONSE_MAX;
1616 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1617 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1620 if (!strncmp(string, "ping", 4))
1622 if (developer.integer >= 10)
1623 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1624 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1627 if (!strncmp(string, "ack", 3))
1629 // QuakeWorld compatibility
1630 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1632 // challenge message
1633 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1634 M_Update_Return_Reason("Got QuakeWorld challenge response");
1635 cls.qw_qport = qport.integer;
1636 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1637 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1638 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1641 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1644 M_Update_Return_Reason("QuakeWorld Accepted");
1645 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1648 if (length > 2 && !memcmp(string, "n\\", 2))
1650 serverlist_info_t *info;
1654 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1655 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1658 // search the cache for this server and update it
1659 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1663 info = &serverlist_cache[n].info;
1664 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1665 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1666 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1667 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1669 info->numplayers = 0; // updated below
1670 info->numhumans = 0; // updated below
1671 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1672 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1674 // count active players on server
1675 // (we could gather more info, but we're just after the number)
1676 s = strchr(string, '\n');
1680 while (s < string + length)
1682 for (;s < string + length && *s != '\n';s++)
1684 if (s >= string + length)
1692 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1696 if (string[0] == 'n')
1699 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1701 // we may not have liked the packet, but it was a command packet, so
1702 // we're done processing this packet now
1705 // quakeworld ingame packet
1706 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1709 CL_ParseServerMessage();
1712 // netquake control packets, supported for compatibility only
1713 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1716 serverlist_info_t *info;
1720 SZ_Clear(&net_message);
1721 SZ_Write(&net_message, data, length);
1727 if (developer.integer >= 10)
1728 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1729 if (cls.connect_trying)
1731 lhnetaddress_t clientportaddress;
1732 clientportaddress = *peeraddress;
1733 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1734 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1735 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1736 M_Update_Return_Reason("Accepted");
1737 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1741 if (developer.integer >= 10)
1742 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1743 cls.connect_trying = false;
1744 M_Update_Return_Reason((char *)MSG_ReadString());
1746 case CCREP_SERVER_INFO:
1747 if (developer.integer >= 10)
1748 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1749 // LordHavoc: because the quake server may report weird addresses
1750 // we just ignore it and keep the real address
1752 // search the cache for this server and update it
1753 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1757 info = &serverlist_cache[n].info;
1758 strlcpy(info->game, "Quake", sizeof(info->game));
1759 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1760 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1761 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1762 info->numplayers = MSG_ReadByte();
1763 info->maxplayers = MSG_ReadByte();
1764 info->protocol = MSG_ReadByte();
1766 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1769 case CCREP_PLAYER_INFO:
1770 // we got a CCREP_PLAYER_INFO??
1771 //if (developer.integer >= 10)
1772 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1774 case CCREP_RULE_INFO:
1775 // we got a CCREP_RULE_INFO??
1776 //if (developer.integer >= 10)
1777 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1782 SZ_Clear(&net_message);
1783 // we may not have liked the packet, but it was a valid control
1784 // packet, so we're done processing this packet now
1788 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1789 CL_ParseServerMessage();
1793 void NetConn_QueryQueueFrame(void)
1799 static double querycounter = 0;
1801 if(!net_slist_pause.integer && serverlist_paused)
1802 ServerList_RebuildViewList();
1803 serverlist_paused = net_slist_pause.integer;
1805 if (serverlist_querysleep)
1808 // apply a cool down time after master server replies,
1809 // to avoid messing up the ping times on the servers
1810 if (serverlist_querywaittime > realtime)
1813 // each time querycounter reaches 1.0 issue a query
1814 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1815 maxqueries = (int)querycounter;
1816 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1817 querycounter -= maxqueries;
1819 if( maxqueries == 0 ) {
1823 // scan serverlist and issue queries as needed
1824 serverlist_querysleep = true;
1826 timeouttime = realtime - net_slist_timeout.value;
1827 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1829 serverlist_entry_t *entry = &serverlist_cache[ index ];
1830 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1835 serverlist_querysleep = false;
1836 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1841 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1843 lhnetaddress_t address;
1846 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1847 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1849 for (socket = 0; socket < cl_numsockets ; socket++)
1850 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1854 for (socket = 0; socket < cl_numsockets ; socket++)
1855 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1858 // update the entry fields
1859 entry->querytime = realtime;
1860 entry->querycounter++;
1862 // if not in the slist menu we should print the server to console
1863 if (serverlist_consoleoutput)
1864 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1870 // have we tried to refresh this server?
1871 if( entry->query == SQS_REFRESHING ) {
1872 // yes, so update the reply count (since its not responding anymore)
1874 if(!serverlist_paused)
1875 ServerList_ViewList_Remove(entry);
1877 entry->query = SQS_TIMEDOUT;
1882 void NetConn_ClientFrame(void)
1885 lhnetaddress_t peeraddress;
1886 NetConn_UpdateSockets();
1887 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1889 if (cls.connect_remainingtries == 0)
1890 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1891 cls.connect_nextsendtime = realtime + 1;
1892 cls.connect_remainingtries--;
1893 if (cls.connect_remainingtries <= -10)
1895 cls.connect_trying = false;
1896 M_Update_Return_Reason("Connect: Failed");
1899 // try challenge first (newer DP server or QW)
1900 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1901 // then try netquake as a fallback (old server, or netquake)
1902 SZ_Clear(&net_message);
1903 // save space for the header, filled in later
1904 MSG_WriteLong(&net_message, 0);
1905 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1906 MSG_WriteString(&net_message, "QUAKE");
1907 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1908 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1909 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1910 SZ_Clear(&net_message);
1912 for (i = 0;i < cl_numsockets;i++)
1913 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1914 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1915 NetConn_QueryQueueFrame();
1916 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1918 Con_Print("Connection timed out\n");
1920 Host_ShutdownServer ();
1924 #define MAX_CHALLENGES 128
1927 lhnetaddress_t address;
1931 challenge[MAX_CHALLENGES];
1933 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1937 for (i = 0;i < bufferlength - 1;i++)
1941 c = rand () % (127 - 33) + 33;
1942 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1948 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
1949 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1952 unsigned int nb_clients = 0, nb_bots = 0, i;
1958 // How many clients are there?
1959 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1961 if (svs.clients[i].active)
1964 if (!svs.clients[i].netconnection)
1970 if(prog->globaloffsets.worldstatus >= 0)
1972 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
1978 for(q = str; *q; ++q)
1979 if(*q != '\\' && *q != '\n')
1985 // TODO: we should add more information for the full status string
1986 length = dpsnprintf(out_msg, out_size,
1987 "\377\377\377\377%s\x0A"
1988 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1989 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1993 fullstatus ? "statusResponse" : "infoResponse",
1994 gamename, com_modname, gameversion.integer, svs.maxclients,
1995 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1996 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
1997 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1998 fullstatus ? "\n" : "");
2000 // Make sure it fits in the buffer
2010 savelength = length;
2012 ptr = out_msg + length;
2013 left = (int)out_size - length;
2015 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2017 client_t *cl = &svs.clients[i];
2020 int nameind, cleanind, pingvalue;
2022 char cleanname [sizeof(cl->name)];
2024 // Remove all characters '"' and '\' in the player name
2029 curchar = cl->name[nameind++];
2030 if (curchar != '"' && curchar != '\\')
2032 cleanname[cleanind++] = curchar;
2033 if (cleanind == sizeof(cleanname) - 1)
2036 } while (curchar != '\0');
2037 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2039 pingvalue = (int)(cl->ping * 1000.0f);
2040 if(cl->netconnection)
2041 pingvalue = bound(1, pingvalue, 9999);
2046 if(prog->fieldoffsets.clientstatus >= 0)
2048 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2054 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2055 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2061 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2063 if(cl->frags == -666) // spectator
2064 strlcpy(teambuf, " 0", sizeof(teambuf));
2065 else if(cl->colors == 0x44) // red team
2066 strlcpy(teambuf, " 1", sizeof(teambuf));
2067 else if(cl->colors == 0xDD) // blue team
2068 strlcpy(teambuf, " 2", sizeof(teambuf));
2069 else if(cl->colors == 0xCC) // yellow team
2070 strlcpy(teambuf, " 3", sizeof(teambuf));
2071 else if(cl->colors == 0x99) // pink team
2072 strlcpy(teambuf, " 4", sizeof(teambuf));
2074 strlcpy(teambuf, " 0", sizeof(teambuf));
2079 // note: team number is inserted according to SoF2 protocol
2081 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2087 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2096 // turn it into an infoResponse!
2097 out_msg[savelength] = 0;
2098 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2099 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2116 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2118 int floodslotnum, bestfloodslotnum;
2119 double bestfloodtime;
2120 lhnetaddress_t noportpeeraddress;
2121 // see if this is a connect flood
2122 noportpeeraddress = *peeraddress;
2123 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2124 bestfloodslotnum = 0;
2125 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2126 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2128 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2130 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2131 bestfloodslotnum = floodslotnum;
2133 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2135 // this address matches an ongoing flood address
2136 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2138 // renew the ban on this address so it does not expire
2139 // until the flood has subsided
2140 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2141 //Con_Printf("Flood detected!\n");
2144 // the flood appears to have subsided, so allow this
2145 bestfloodslotnum = floodslotnum; // reuse the same slot
2149 // begin a new timeout on this address
2150 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2151 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2152 //Con_Printf("Flood detection initiated!\n");
2156 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2159 lhnetaddress_t noportpeeraddress;
2160 // see if this is a connect flood
2161 noportpeeraddress = *peeraddress;
2162 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2163 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2165 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2167 // this address matches an ongoing flood address
2169 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2170 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2171 //Con_Printf("Flood cleared!\n");
2176 // returns a string describing the user level, or NULL for auth failure
2177 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos)
2182 if(!strcmp(rcon_password.string, password))
2185 if(strcmp(rcon_restricted_password.string, password))
2188 for(text = s; text != endpos; ++text)
2189 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2190 return NULL; // block possible exploits against the parser/alias expansion
2194 size_t l = strlen(s);
2197 hasquotes = (strchr(s, '"') != NULL);
2198 // sorry, we can't allow these substrings in wildcard expressions,
2199 // as they can mess with the argument counts
2200 text = rcon_restricted_commands.string;
2201 while(COM_ParseToken_Console(&text))
2203 // com_token now contains a pattern to check for...
2204 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2207 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2210 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2212 if(!strcmp(com_token, s))
2215 else // single-arg expression? must match the beginning of the command
2217 if(!strcmp(com_token, s))
2219 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2223 // if we got here, nothing matched!
2230 return "restricted rcon";
2233 extern void SV_SendServerinfo (client_t *client);
2234 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2236 int i, ret, clientnum, best;
2239 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2240 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2245 // convert the address to a string incase we need it
2246 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2248 // see if we can identify the sender as a local player
2249 // (this is necessary for rcon to send a reliable reply if the client is
2250 // actually on the server, not sending remotely)
2251 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2252 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2254 if (i == svs.maxclients)
2257 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2259 // received a command string - strip off the packaging and put it
2260 // into our string buffer with NULL termination
2263 length = min(length, (int)sizeof(stringbuf) - 1);
2264 memcpy(stringbuf, data, length);
2265 stringbuf[length] = 0;
2268 if (developer.integer >= 10)
2270 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2271 Com_HexDumpToConsole(data, length);
2274 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2276 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2278 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2280 if (besttime > challenge[i].time)
2281 besttime = challenge[best = i].time;
2283 // if we did not find an exact match, choose the oldest and
2284 // update address and string
2285 if (i == MAX_CHALLENGES)
2288 challenge[i].address = *peeraddress;
2289 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2291 challenge[i].time = realtime;
2292 // send the challenge
2293 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2296 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2301 if (!(s = SearchInfostring(string, "challenge")))
2303 // validate the challenge
2304 for (i = 0;i < MAX_CHALLENGES;i++)
2305 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2307 // if the challenge is not recognized, drop the packet
2308 if (i == MAX_CHALLENGES)
2311 // check engine protocol
2312 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2314 if (developer.integer >= 10)
2315 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2316 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2320 // see if this is a duplicate connection request or a disconnected
2321 // client who is rejoining to the same client slot
2322 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2324 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2326 // this is a known client...
2327 if (client->spawned)
2329 // client crashed and is coming back,
2330 // keep their stuff intact
2331 if (developer.integer >= 10)
2332 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2333 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2335 SV_SendServerinfo(client);
2340 // client is still trying to connect,
2341 // so we send a duplicate reply
2342 if (developer.integer >= 10)
2343 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2344 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2350 if (NetConn_PreventConnectFlood(peeraddress))
2353 // find an empty client slot for this new client
2354 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2357 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2359 // allocated connection
2360 if (developer.integer >= 10)
2361 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2362 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2363 // now set up the client
2365 SV_ConnectClient(clientnum, conn);
2367 NetConn_Heartbeat(1);
2372 // no empty slots found - server is full
2373 if (developer.integer >= 10)
2374 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2375 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2379 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2381 const char *challenge = NULL;
2383 // If there was a challenge in the getinfo message
2384 if (length > 8 && string[7] == ' ')
2385 challenge = string + 8;
2387 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2389 if (developer.integer >= 10)
2390 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2391 NetConn_WriteString(mysocket, response, peeraddress);
2395 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2397 const char *challenge = NULL;
2399 // If there was a challenge in the getinfo message
2400 if (length > 10 && string[9] == ' ')
2401 challenge = string + 10;
2403 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2405 if (developer.integer >= 10)
2406 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2407 NetConn_WriteString(mysocket, response, peeraddress);
2411 if (length >= 5 && !memcmp(string, "rcon ", 5))
2414 char *s = string + 5;
2415 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2417 for (i = 0;!ISWHITESPACE(*s);s++)
2418 if (i < (int)sizeof(password) - 1)
2420 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2423 if (!ISWHITESPACE(password[0]))
2425 const char *userlevel = RCon_Authenticate(password, s, endpos);
2428 // looks like a legitimate rcon command with the correct password
2430 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2431 while(s_ptr != endpos)
2433 size_t l = strlen(s_ptr);
2435 Con_Printf(" %s;", s_ptr);
2440 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2441 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2444 size_t l = strlen(s);
2447 client_t *host_client_save = host_client;
2448 Cmd_ExecuteString(s, src_command);
2449 host_client = host_client_save;
2450 // in case it is a command that changes host_client (like restart)
2454 Con_Rcon_Redirect_End();
2458 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2463 if (!strncmp(string, "ping", 4))
2465 if (developer.integer >= 10)
2466 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2467 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2470 if (!strncmp(string, "ack", 3))
2472 // we may not have liked the packet, but it was a command packet, so
2473 // we're done processing this packet now
2476 // netquake control packets, supported for compatibility only, and only
2477 // when running game protocols that are normally served via this connection
2479 // (this protects more modern protocols against being used for
2480 // Quake packet flood Denial Of Service attacks)
2481 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))
2485 const char *protocolname;
2488 SZ_Clear(&net_message);
2489 SZ_Write(&net_message, data, length);
2495 if (developer.integer >= 10)
2496 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2497 if(!islocal && sv_public.integer <= -2)
2500 protocolname = MSG_ReadString();
2501 protocolnumber = MSG_ReadByte();
2502 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2504 if (developer.integer >= 10)
2505 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2506 SZ_Clear(&net_message);
2507 // save space for the header, filled in later
2508 MSG_WriteLong(&net_message, 0);
2509 MSG_WriteByte(&net_message, CCREP_REJECT);
2510 MSG_WriteString(&net_message, "Incompatible version.\n");
2511 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2512 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2513 SZ_Clear(&net_message);
2517 // see if this connect request comes from a known client
2518 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2520 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2522 // this is either a duplicate connection request
2523 // or coming back from a timeout
2524 // (if so, keep their stuff intact)
2527 if (developer.integer >= 10)
2528 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2529 SZ_Clear(&net_message);
2530 // save space for the header, filled in later
2531 MSG_WriteLong(&net_message, 0);
2532 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2533 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2534 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2535 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2536 SZ_Clear(&net_message);
2538 // if client is already spawned, re-send the
2539 // serverinfo message as they'll need it to play
2540 if (client->spawned)
2543 SV_SendServerinfo(client);
2550 // this is a new client, check for connection flood
2551 if (NetConn_PreventConnectFlood(peeraddress))
2554 // find a slot for the new client
2555 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2558 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2560 // connect to the client
2561 // everything is allocated, just fill in the details
2562 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2563 if (developer.integer >= 10)
2564 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2565 // send back the info about the server connection
2566 SZ_Clear(&net_message);
2567 // save space for the header, filled in later
2568 MSG_WriteLong(&net_message, 0);
2569 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2570 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2571 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2572 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2573 SZ_Clear(&net_message);
2574 // now set up the client struct
2576 SV_ConnectClient(clientnum, conn);
2578 NetConn_Heartbeat(1);
2583 if (developer.integer >= 10)
2584 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2585 // no room; try to let player know
2586 SZ_Clear(&net_message);
2587 // save space for the header, filled in later
2588 MSG_WriteLong(&net_message, 0);
2589 MSG_WriteByte(&net_message, CCREP_REJECT);
2590 MSG_WriteString(&net_message, "Server is full.\n");
2591 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2592 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2593 SZ_Clear(&net_message);
2595 case CCREQ_SERVER_INFO:
2596 if (developer.integer >= 10)
2597 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2598 if(!islocal && sv_public.integer <= -1)
2600 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2603 char myaddressstring[128];
2604 if (developer.integer >= 10)
2605 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2606 SZ_Clear(&net_message);
2607 // save space for the header, filled in later
2608 MSG_WriteLong(&net_message, 0);
2609 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2610 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2611 MSG_WriteString(&net_message, myaddressstring);
2612 MSG_WriteString(&net_message, hostname.string);
2613 MSG_WriteString(&net_message, sv.name);
2614 // How many clients are there?
2615 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2616 if (svs.clients[i].active)
2618 MSG_WriteByte(&net_message, numclients);
2619 MSG_WriteByte(&net_message, svs.maxclients);
2620 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2621 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2622 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2623 SZ_Clear(&net_message);
2626 case CCREQ_PLAYER_INFO:
2627 if (developer.integer >= 10)
2628 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2629 if(!islocal && sv_public.integer <= -1)
2633 int playerNumber, activeNumber, clientNumber;
2636 playerNumber = MSG_ReadByte();
2638 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2639 if (client->active && ++activeNumber == playerNumber)
2641 if (clientNumber != svs.maxclients)
2643 SZ_Clear(&net_message);
2644 // save space for the header, filled in later
2645 MSG_WriteLong(&net_message, 0);
2646 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2647 MSG_WriteByte(&net_message, playerNumber);
2648 MSG_WriteString(&net_message, client->name);
2649 MSG_WriteLong(&net_message, client->colors);
2650 MSG_WriteLong(&net_message, client->frags);
2651 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2652 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2653 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2654 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2655 SZ_Clear(&net_message);
2659 case CCREQ_RULE_INFO:
2660 if (developer.integer >= 10)
2661 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2662 if(!islocal && sv_public.integer <= -1)
2669 // find the search start location
2670 prevCvarName = MSG_ReadString();
2671 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2673 // send the response
2674 SZ_Clear(&net_message);
2675 // save space for the header, filled in later
2676 MSG_WriteLong(&net_message, 0);
2677 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2680 MSG_WriteString(&net_message, var->name);
2681 MSG_WriteString(&net_message, var->string);
2683 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2684 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2685 SZ_Clear(&net_message);
2691 SZ_Clear(&net_message);
2692 // we may not have liked the packet, but it was a valid control
2693 // packet, so we're done processing this packet now
2698 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2701 SV_ReadClientMessage();
2709 void NetConn_ServerFrame(void)
2712 lhnetaddress_t peeraddress;
2713 for (i = 0;i < sv_numsockets;i++)
2714 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2715 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2716 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2718 // never timeout loopback connections
2719 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2721 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2723 SV_DropClient(false);
2729 void NetConn_SleepMicroseconds(int microseconds)
2731 LHNET_SleepUntilPacket_Microseconds(microseconds);
2734 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2738 lhnetaddress_t masteraddress;
2739 lhnetaddress_t broadcastaddress;
2740 lhnetaddress_t serveraddress;
2744 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2747 // 26000 is the default quake server port, servers on other ports will not
2749 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2750 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2754 for (i = 0;i < cl_numsockets;i++)
2758 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2760 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2762 // search LAN for Quake servers
2763 SZ_Clear(&net_message);
2764 // save space for the header, filled in later
2765 MSG_WriteLong(&net_message, 0);
2766 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2767 MSG_WriteString(&net_message, "QUAKE");
2768 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2769 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2770 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2771 SZ_Clear(&net_message);
2773 // search LAN for DarkPlaces servers
2774 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2777 // build the getservers message to send to the dpmaster master servers
2778 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2781 for (masternum = 0;sv_masters[masternum].name;masternum++)
2783 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2786 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2790 // search favorite servers
2791 text = net_slist_favorites.string;
2792 while(COM_ParseToken_Console(&text))
2794 if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2796 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, com_token, true );
2803 // only query QuakeWorld servers when the user wants to
2806 for (i = 0;i < cl_numsockets;i++)
2810 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2812 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2814 // search LAN for QuakeWorld servers
2815 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2817 // build the getservers message to send to the qwmaster master servers
2818 // note this has no -1 prefix, and the trailing nul byte is sent
2819 dpsnprintf(request, sizeof(request), "c\n");
2823 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2825 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2827 if (m_state != m_slist)
2829 char lookupstring[128];
2830 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2831 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2834 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2838 // search favorite servers
2839 text = net_slist_favorites.string;
2840 while(COM_ParseToken_Console(&text))
2842 if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2844 // writing AND querying to catch replies for both
2845 // protocols (in case DP has been queried above, this
2846 // would only try the DP protocol otherwise)
2847 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &serveraddress);
2848 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, com_token, true );
2854 if (!masterquerycount)
2856 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2857 M_Update_Return_Reason("No network");
2861 void NetConn_Heartbeat(int priority)
2863 lhnetaddress_t masteraddress;
2865 lhnetsocket_t *mysocket;
2867 // if it's a state change (client connected), limit next heartbeat to no
2868 // more than 30 sec in the future
2869 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2870 nextheartbeattime = realtime + 30.0;
2872 // limit heartbeatperiod to 30 to 270 second range,
2873 // lower limit is to avoid abusing master servers with excess traffic,
2874 // upper limit is to avoid timing out on the master server (which uses
2876 if (sv_heartbeatperiod.value < 30)
2877 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2878 if (sv_heartbeatperiod.value > 270)
2879 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2881 // make advertising optional and don't advertise singleplayer games, and
2882 // only send a heartbeat as often as the admin wants
2883 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2885 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2886 for (masternum = 0;sv_masters[masternum].name;masternum++)
2887 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2888 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2892 static void Net_Heartbeat_f(void)
2895 NetConn_Heartbeat(2);
2897 Con_Print("No server running, can not heartbeat to master server.\n");
2900 void PrintStats(netconn_t *conn)
2902 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2903 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
2905 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2908 void Net_Stats_f(void)
2911 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2912 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2913 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2914 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2915 Con_Printf("packetsSent = %i\n", packetsSent);
2916 Con_Printf("packetsReSent = %i\n", packetsReSent);
2917 Con_Printf("packetsReceived = %i\n", packetsReceived);
2918 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2919 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2920 Con_Print("connections =\n");
2921 for (conn = netconn_list;conn;conn = conn->next)
2925 void Net_Refresh_f(void)
2927 if (m_state != m_slist) {
2928 Con_Print("Sending new requests to master servers\n");
2929 ServerList_QueryList(false, true, false, true);
2930 Con_Print("Listening for replies...\n");
2932 ServerList_QueryList(false, true, false, false);
2935 void Net_Slist_f(void)
2937 ServerList_ResetMasks();
2938 serverlist_sortbyfield = SLIF_PING;
2939 serverlist_sortflags = 0;
2940 if (m_state != m_slist) {
2941 Con_Print("Sending requests to master servers\n");
2942 ServerList_QueryList(true, true, false, true);
2943 Con_Print("Listening for replies...\n");
2945 ServerList_QueryList(true, true, false, false);
2948 void Net_SlistQW_f(void)
2950 ServerList_ResetMasks();
2951 serverlist_sortbyfield = SLIF_PING;
2952 serverlist_sortflags = 0;
2953 if (m_state != m_slist) {
2954 Con_Print("Sending requests to master servers\n");
2955 ServerList_QueryList(true, false, true, true);
2956 serverlist_consoleoutput = true;
2957 Con_Print("Listening for replies...\n");
2959 ServerList_QueryList(true, false, true, false);
2962 void NetConn_Init(void)
2965 lhnetaddress_t tempaddress;
2966 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2967 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2968 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2969 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2970 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
2971 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2972 Cvar_RegisterVariable(&rcon_restricted_password);
2973 Cvar_RegisterVariable(&rcon_restricted_commands);
2974 Cvar_RegisterVariable(&net_slist_queriespersecond);
2975 Cvar_RegisterVariable(&net_slist_queriesperframe);
2976 Cvar_RegisterVariable(&net_slist_timeout);
2977 Cvar_RegisterVariable(&net_slist_maxtries);
2978 Cvar_RegisterVariable(&net_slist_favorites);
2979 Cvar_RegisterVariable(&net_slist_pause);
2980 Cvar_RegisterVariable(&net_messagetimeout);
2981 Cvar_RegisterVariable(&net_connecttimeout);
2982 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2983 Cvar_RegisterVariable(&cl_netlocalping);
2984 Cvar_RegisterVariable(&cl_netpacketloss_send);
2985 Cvar_RegisterVariable(&cl_netpacketloss_receive);
2986 Cvar_RegisterVariable(&hostname);
2987 Cvar_RegisterVariable(&developer_networking);
2988 Cvar_RegisterVariable(&cl_netport);
2989 Cvar_RegisterVariable(&sv_netport);
2990 Cvar_RegisterVariable(&net_address);
2991 //Cvar_RegisterVariable(&net_address_ipv6);
2992 Cvar_RegisterVariable(&sv_public);
2993 Cvar_RegisterVariable(&sv_heartbeatperiod);
2994 for (i = 0;sv_masters[i].name;i++)
2995 Cvar_RegisterVariable(&sv_masters[i]);
2996 Cvar_RegisterVariable(&gameversion);
2997 // 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.
2998 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3000 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3002 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3003 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3006 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3008 // 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
3009 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3011 i = atoi(com_argv[i + 1]);
3012 if (i >= 0 && i < 65536)
3014 Con_Printf("-port option used, setting port cvar to %i\n", i);
3015 Cvar_SetValueQuick(&sv_netport, i);
3018 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3022 net_message.data = net_message_buf;
3023 net_message.maxsize = sizeof(net_message_buf);
3024 net_message.cursize = 0;
3028 void NetConn_Shutdown(void)
3030 NetConn_CloseClientPorts();
3031 NetConn_CloseServerPorts();