2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define QWMASTER_PORT 27000
27 #define DPMASTER_PORT 27950
29 // note this defaults on for dedicated servers, off for listen servers
30 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
31 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
33 static cvar_t sv_masters [] =
35 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
36 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
37 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
38 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
39 {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40 {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
41 {0, "sv_masterextra3", "dpmaster.tchr.no", "default master server 3 (admin: tChr)"}, // admin: tChr
45 static cvar_t sv_qwmasters [] =
47 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
48 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
49 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
50 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
51 {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
52 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
53 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
54 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
55 {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
59 static double nextheartbeattime = 0;
61 sizebuf_t net_message;
62 static unsigned char net_message_buf[NET_MAXMESSAGE];
64 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
65 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
66 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
67 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
68 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
70 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
71 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
72 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
73 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
74 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
75 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
76 static cvar_t net_slist_pause = {0, "net_slist_pause", "0", "when set to 1, the server list won't update until it is set back to 0"};
77 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
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 = max(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)
1951 const char *qcstatus = NULL;
1952 unsigned int nb_clients = 0, nb_bots = 0, i;
1957 // How many clients are there?
1958 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1960 if (svs.clients[i].active)
1963 if (!svs.clients[i].netconnection)
1968 if(prog->globaloffsets.worldstatus >= 0)
1970 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
1975 qcstatus = p = Mem_Alloc(tempmempool, strlen(str) + 1);
1976 for(q = str; *q; ++q)
1983 // TODO: we should add more information for the full status string
1984 length = dpsnprintf(out_msg, out_size,
1985 "\377\377\377\377%s\x0A"
1986 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1987 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1991 fullstatus ? "statusResponse" : "infoResponse",
1992 gamename, com_modname, gameversion.integer, svs.maxclients,
1993 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1994 qcstatus ? "\\qcstatus\\" : "", qcstatus ? qcstatus : "",
1995 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1996 fullstatus ? "\n" : "");
2000 Mem_Free((char *)qcstatus);
2004 // Make sure it fits in the buffer
2014 savelength = length;
2016 ptr = out_msg + length;
2017 left = (int)out_size - length;
2019 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2021 client_t *cl = &svs.clients[i];
2024 int nameind, cleanind, pingvalue;
2026 char cleanname [sizeof(cl->name)];
2028 // Remove all characters '"' and '\' in the player name
2033 curchar = cl->name[nameind++];
2034 if (curchar != '"' && curchar != '\\')
2036 cleanname[cleanind++] = curchar;
2037 if (cleanind == sizeof(cleanname) - 1)
2040 } while (curchar != '\0');
2042 pingvalue = (int)(cl->ping * 1000.0f);
2043 if(cl->netconnection)
2044 pingvalue = bound(1, pingvalue, 9999);
2048 if(prog->fieldoffsets.clientstatus >= 0)
2050 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2055 qcstatus = p = Mem_Alloc(tempmempool, strlen(str) + 1);
2056 for(q = str; *q; ++q)
2057 if(*q != '\\' && *q != ' ')
2065 length = dpsnprintf(ptr, left, "%s %d \"%s\"\n",
2069 Mem_Free((char *)qcstatus);
2073 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
2081 // turn it into an infoResponse!
2082 out_msg[savelength] = 0;
2083 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2084 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2101 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2103 int floodslotnum, bestfloodslotnum;
2104 double bestfloodtime;
2105 lhnetaddress_t noportpeeraddress;
2106 // see if this is a connect flood
2107 noportpeeraddress = *peeraddress;
2108 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2109 bestfloodslotnum = 0;
2110 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2111 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2113 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2115 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2116 bestfloodslotnum = floodslotnum;
2118 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2120 // this address matches an ongoing flood address
2121 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2123 // renew the ban on this address so it does not expire
2124 // until the flood has subsided
2125 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2126 //Con_Printf("Flood detected!\n");
2129 // the flood appears to have subsided, so allow this
2130 bestfloodslotnum = floodslotnum; // reuse the same slot
2134 // begin a new timeout on this address
2135 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2136 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2137 //Con_Printf("Flood detection initiated!\n");
2141 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2144 lhnetaddress_t noportpeeraddress;
2145 // see if this is a connect flood
2146 noportpeeraddress = *peeraddress;
2147 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2148 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2150 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2152 // this address matches an ongoing flood address
2154 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2155 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2156 //Con_Printf("Flood cleared!\n");
2161 // returns a string describing the user level, or NULL for auth failure
2162 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos)
2167 if(!strcmp(rcon_password.string, password))
2170 if(strcmp(rcon_restricted_password.string, password))
2173 for(text = s; text != endpos; ++text)
2174 if(*text > 0 && (*text < ' ' || *text == ';'))
2175 return NULL; // block possible exploits against the parser/alias expansion
2179 size_t l = strlen(s);
2182 hasquotes = (strchr(s, '"') != NULL);
2183 // sorry, we can't allow these substrings in wildcard expressions,
2184 // as they can mess with the argument counts
2185 text = rcon_restricted_commands.string;
2186 while(COM_ParseToken_Console(&text))
2188 // com_token now contains a pattern to check for...
2189 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2192 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2195 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2197 if(!strcmp(com_token, s))
2200 else // single-arg expression? must match the beginning of the command
2202 if(!strcmp(com_token, s))
2204 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2208 // if we got here, nothing matched!
2215 return "restricted rcon";
2218 extern void SV_SendServerinfo (client_t *client);
2219 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2221 int i, ret, clientnum, best;
2224 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2225 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2230 // convert the address to a string incase we need it
2231 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2233 // see if we can identify the sender as a local player
2234 // (this is necessary for rcon to send a reliable reply if the client is
2235 // actually on the server, not sending remotely)
2236 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2237 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2239 if (i == svs.maxclients)
2242 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2244 // received a command string - strip off the packaging and put it
2245 // into our string buffer with NULL termination
2248 length = min(length, (int)sizeof(stringbuf) - 1);
2249 memcpy(stringbuf, data, length);
2250 stringbuf[length] = 0;
2253 if (developer.integer >= 10)
2255 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2256 Com_HexDumpToConsole(data, length);
2259 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2261 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2263 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2265 if (besttime > challenge[i].time)
2266 besttime = challenge[best = i].time;
2268 // if we did not find an exact match, choose the oldest and
2269 // update address and string
2270 if (i == MAX_CHALLENGES)
2273 challenge[i].address = *peeraddress;
2274 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2276 challenge[i].time = realtime;
2277 // send the challenge
2278 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2281 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2286 if (!(s = SearchInfostring(string, "challenge")))
2288 // validate the challenge
2289 for (i = 0;i < MAX_CHALLENGES;i++)
2290 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2292 // if the challenge is not recognized, drop the packet
2293 if (i == MAX_CHALLENGES)
2296 // check engine protocol
2297 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
2299 if (developer.integer >= 10)
2300 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2301 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2305 // see if this is a duplicate connection request or a disconnected
2306 // client who is rejoining to the same client slot
2307 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2309 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2311 // this is a known client...
2312 if (client->spawned)
2314 // client crashed and is coming back,
2315 // keep their stuff intact
2316 if (developer.integer >= 10)
2317 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2318 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2320 SV_SendServerinfo(client);
2325 // client is still trying to connect,
2326 // so we send a duplicate reply
2327 if (developer.integer >= 10)
2328 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2329 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2335 if (NetConn_PreventConnectFlood(peeraddress))
2338 // find an empty client slot for this new client
2339 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2342 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2344 // allocated connection
2345 if (developer.integer >= 10)
2346 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2347 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2348 // now set up the client
2350 SV_ConnectClient(clientnum, conn);
2352 NetConn_Heartbeat(1);
2357 // no empty slots found - server is full
2358 if (developer.integer >= 10)
2359 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2360 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2364 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2366 const char *challenge = NULL;
2368 // If there was a challenge in the getinfo message
2369 if (length > 8 && string[7] == ' ')
2370 challenge = string + 8;
2372 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2374 if (developer.integer >= 10)
2375 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2376 NetConn_WriteString(mysocket, response, peeraddress);
2380 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2382 const char *challenge = NULL;
2384 // If there was a challenge in the getinfo message
2385 if (length > 10 && string[9] == ' ')
2386 challenge = string + 10;
2388 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2390 if (developer.integer >= 10)
2391 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2392 NetConn_WriteString(mysocket, response, peeraddress);
2396 if (length >= 5 && !memcmp(string, "rcon ", 5))
2399 char *s = string + 5;
2400 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2402 for (i = 0;*s > ' ';s++)
2403 if (i < (int)sizeof(password) - 1)
2405 if(*s <= ' ' && s != endpos) // skip leading ugly space
2408 if (password[0] > ' ')
2410 const char *userlevel = RCon_Authenticate(password, s, endpos);
2413 // looks like a legitimate rcon command with the correct password
2415 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2416 while(s_ptr != endpos)
2418 size_t l = strlen(s_ptr);
2420 Con_Printf(" %s;", s_ptr);
2425 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2426 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2429 size_t l = strlen(s);
2432 client_t *host_client_save = host_client;
2433 Cmd_ExecuteString(s, src_command);
2434 host_client = host_client_save;
2435 // in case it is a command that changes host_client (like restart)
2439 Con_Rcon_Redirect_End();
2443 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2448 if (!strncmp(string, "ping", 4))
2450 if (developer.integer >= 10)
2451 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2452 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2455 if (!strncmp(string, "ack", 3))
2457 // we may not have liked the packet, but it was a command packet, so
2458 // we're done processing this packet now
2461 // netquake control packets, supported for compatibility only, and only
2462 // when running game protocols that are normally served via this connection
2464 // (this protects more modern protocols against being used for
2465 // Quake packet flood Denial Of Service attacks)
2466 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))
2470 const char *protocolname;
2473 SZ_Clear(&net_message);
2474 SZ_Write(&net_message, data, length);
2480 if (developer.integer >= 10)
2481 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2482 if(!islocal && sv_public.integer <= -2)
2485 protocolname = MSG_ReadString();
2486 protocolnumber = MSG_ReadByte();
2487 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2489 if (developer.integer >= 10)
2490 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2491 SZ_Clear(&net_message);
2492 // save space for the header, filled in later
2493 MSG_WriteLong(&net_message, 0);
2494 MSG_WriteByte(&net_message, CCREP_REJECT);
2495 MSG_WriteString(&net_message, "Incompatible version.\n");
2496 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2497 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2498 SZ_Clear(&net_message);
2502 // see if this connect request comes from a known client
2503 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2505 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2507 // this is either a duplicate connection request
2508 // or coming back from a timeout
2509 // (if so, keep their stuff intact)
2512 if (developer.integer >= 10)
2513 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2514 SZ_Clear(&net_message);
2515 // save space for the header, filled in later
2516 MSG_WriteLong(&net_message, 0);
2517 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2518 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2519 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2520 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2521 SZ_Clear(&net_message);
2523 // if client is already spawned, re-send the
2524 // serverinfo message as they'll need it to play
2525 if (client->spawned)
2528 SV_SendServerinfo(client);
2535 // this is a new client, check for connection flood
2536 if (NetConn_PreventConnectFlood(peeraddress))
2539 // find a slot for the new client
2540 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2543 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2545 // connect to the client
2546 // everything is allocated, just fill in the details
2547 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2548 if (developer.integer >= 10)
2549 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2550 // send back the info about the server connection
2551 SZ_Clear(&net_message);
2552 // save space for the header, filled in later
2553 MSG_WriteLong(&net_message, 0);
2554 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2555 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2556 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2557 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2558 SZ_Clear(&net_message);
2559 // now set up the client struct
2561 SV_ConnectClient(clientnum, conn);
2563 NetConn_Heartbeat(1);
2568 if (developer.integer >= 10)
2569 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2570 // no room; try to let player know
2571 SZ_Clear(&net_message);
2572 // save space for the header, filled in later
2573 MSG_WriteLong(&net_message, 0);
2574 MSG_WriteByte(&net_message, CCREP_REJECT);
2575 MSG_WriteString(&net_message, "Server is full.\n");
2576 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2577 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2578 SZ_Clear(&net_message);
2580 case CCREQ_SERVER_INFO:
2581 if (developer.integer >= 10)
2582 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2583 if(!islocal && sv_public.integer <= -1)
2585 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2588 char myaddressstring[128];
2589 if (developer.integer >= 10)
2590 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2591 SZ_Clear(&net_message);
2592 // save space for the header, filled in later
2593 MSG_WriteLong(&net_message, 0);
2594 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2595 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2596 MSG_WriteString(&net_message, myaddressstring);
2597 MSG_WriteString(&net_message, hostname.string);
2598 MSG_WriteString(&net_message, sv.name);
2599 // How many clients are there?
2600 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2601 if (svs.clients[i].active)
2603 MSG_WriteByte(&net_message, numclients);
2604 MSG_WriteByte(&net_message, svs.maxclients);
2605 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2606 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2607 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2608 SZ_Clear(&net_message);
2611 case CCREQ_PLAYER_INFO:
2612 if (developer.integer >= 10)
2613 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2614 if(!islocal && sv_public.integer <= -1)
2618 int playerNumber, activeNumber, clientNumber;
2621 playerNumber = MSG_ReadByte();
2623 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2624 if (client->active && ++activeNumber == playerNumber)
2626 if (clientNumber != svs.maxclients)
2628 SZ_Clear(&net_message);
2629 // save space for the header, filled in later
2630 MSG_WriteLong(&net_message, 0);
2631 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2632 MSG_WriteByte(&net_message, playerNumber);
2633 MSG_WriteString(&net_message, client->name);
2634 MSG_WriteLong(&net_message, client->colors);
2635 MSG_WriteLong(&net_message, client->frags);
2636 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2637 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2638 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2639 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2640 SZ_Clear(&net_message);
2644 case CCREQ_RULE_INFO:
2645 if (developer.integer >= 10)
2646 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2647 if(!islocal && sv_public.integer <= -1)
2654 // find the search start location
2655 prevCvarName = MSG_ReadString();
2656 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2658 // send the response
2659 SZ_Clear(&net_message);
2660 // save space for the header, filled in later
2661 MSG_WriteLong(&net_message, 0);
2662 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2665 MSG_WriteString(&net_message, var->name);
2666 MSG_WriteString(&net_message, var->string);
2668 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2669 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2670 SZ_Clear(&net_message);
2676 SZ_Clear(&net_message);
2677 // we may not have liked the packet, but it was a valid control
2678 // packet, so we're done processing this packet now
2683 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2686 SV_ReadClientMessage();
2694 void NetConn_ServerFrame(void)
2697 lhnetaddress_t peeraddress;
2698 for (i = 0;i < sv_numsockets;i++)
2699 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2700 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2701 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2703 // never timeout loopback connections
2704 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2706 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2708 SV_DropClient(false);
2714 void NetConn_SleepMicroseconds(int microseconds)
2716 LHNET_SleepUntilPacket_Microseconds(microseconds);
2719 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2723 lhnetaddress_t masteraddress;
2724 lhnetaddress_t broadcastaddress;
2725 lhnetaddress_t serveraddress;
2729 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2732 // 26000 is the default quake server port, servers on other ports will not
2734 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2735 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2739 for (i = 0;i < cl_numsockets;i++)
2743 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2745 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2747 // search LAN for Quake servers
2748 SZ_Clear(&net_message);
2749 // save space for the header, filled in later
2750 MSG_WriteLong(&net_message, 0);
2751 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2752 MSG_WriteString(&net_message, "QUAKE");
2753 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2754 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2755 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2756 SZ_Clear(&net_message);
2758 // search LAN for DarkPlaces servers
2759 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2762 // build the getservers message to send to the dpmaster master servers
2763 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2766 for (masternum = 0;sv_masters[masternum].name;masternum++)
2768 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2771 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2775 // search favorite servers
2776 text = net_slist_favorites.string;
2777 while(COM_ParseToken_Console(&text))
2779 if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2781 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, com_token, true );
2788 // only query QuakeWorld servers when the user wants to
2791 for (i = 0;i < cl_numsockets;i++)
2795 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2797 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2799 // search LAN for QuakeWorld servers
2800 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2802 // build the getservers message to send to the qwmaster master servers
2803 // note this has no -1 prefix, and the trailing nul byte is sent
2804 dpsnprintf(request, sizeof(request), "c\n");
2808 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2810 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2812 if (m_state != m_slist)
2814 char lookupstring[128];
2815 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2816 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2819 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2823 // search favorite servers
2824 text = net_slist_favorites.string;
2825 while(COM_ParseToken_Console(&text))
2827 if(LHNETADDRESS_FromString(&serveraddress, com_token, 26000) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2829 // writing AND querying to catch replies for both
2830 // protocols (in case DP has been queried above, this
2831 // would only try the DP protocol otherwise)
2832 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &serveraddress);
2833 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, com_token, true );
2839 if (!masterquerycount)
2841 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2842 M_Update_Return_Reason("No network");
2846 void NetConn_Heartbeat(int priority)
2848 lhnetaddress_t masteraddress;
2850 lhnetsocket_t *mysocket;
2852 // if it's a state change (client connected), limit next heartbeat to no
2853 // more than 30 sec in the future
2854 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2855 nextheartbeattime = realtime + 30.0;
2857 // limit heartbeatperiod to 30 to 270 second range,
2858 // lower limit is to avoid abusing master servers with excess traffic,
2859 // upper limit is to avoid timing out on the master server (which uses
2861 if (sv_heartbeatperiod.value < 30)
2862 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2863 if (sv_heartbeatperiod.value > 270)
2864 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2866 // make advertising optional and don't advertise singleplayer games, and
2867 // only send a heartbeat as often as the admin wants
2868 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2870 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2871 for (masternum = 0;sv_masters[masternum].name;masternum++)
2872 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2873 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2877 static void Net_Heartbeat_f(void)
2880 NetConn_Heartbeat(2);
2882 Con_Print("No server running, can not heartbeat to master server.\n");
2885 void PrintStats(netconn_t *conn)
2887 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2888 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
2890 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2893 void Net_Stats_f(void)
2896 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2897 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2898 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2899 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2900 Con_Printf("packetsSent = %i\n", packetsSent);
2901 Con_Printf("packetsReSent = %i\n", packetsReSent);
2902 Con_Printf("packetsReceived = %i\n", packetsReceived);
2903 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2904 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2905 Con_Print("connections =\n");
2906 for (conn = netconn_list;conn;conn = conn->next)
2910 void Net_Refresh_f(void)
2912 if (m_state != m_slist) {
2913 Con_Print("Sending new requests to master servers\n");
2914 ServerList_QueryList(false, true, false, true);
2915 Con_Print("Listening for replies...\n");
2917 ServerList_QueryList(false, true, false, false);
2920 void Net_Slist_f(void)
2922 ServerList_ResetMasks();
2923 serverlist_sortbyfield = SLIF_PING;
2924 serverlist_sortflags = 0;
2925 if (m_state != m_slist) {
2926 Con_Print("Sending requests to master servers\n");
2927 ServerList_QueryList(true, true, false, true);
2928 Con_Print("Listening for replies...\n");
2930 ServerList_QueryList(true, true, false, false);
2933 void Net_SlistQW_f(void)
2935 ServerList_ResetMasks();
2936 serverlist_sortbyfield = SLIF_PING;
2937 serverlist_sortflags = 0;
2938 if (m_state != m_slist) {
2939 Con_Print("Sending requests to master servers\n");
2940 ServerList_QueryList(true, false, true, true);
2941 serverlist_consoleoutput = true;
2942 Con_Print("Listening for replies...\n");
2944 ServerList_QueryList(true, false, true, false);
2947 void NetConn_Init(void)
2950 lhnetaddress_t tempaddress;
2951 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2952 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2953 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2954 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2955 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
2956 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2957 Cvar_RegisterVariable(&rcon_restricted_password);
2958 Cvar_RegisterVariable(&rcon_restricted_commands);
2959 Cvar_RegisterVariable(&net_slist_queriespersecond);
2960 Cvar_RegisterVariable(&net_slist_queriesperframe);
2961 Cvar_RegisterVariable(&net_slist_timeout);
2962 Cvar_RegisterVariable(&net_slist_maxtries);
2963 Cvar_RegisterVariable(&net_slist_favorites);
2964 Cvar_RegisterVariable(&net_slist_pause);
2965 Cvar_RegisterVariable(&net_messagetimeout);
2966 Cvar_RegisterVariable(&net_connecttimeout);
2967 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2968 Cvar_RegisterVariable(&cl_netlocalping);
2969 Cvar_RegisterVariable(&cl_netpacketloss_send);
2970 Cvar_RegisterVariable(&cl_netpacketloss_receive);
2971 Cvar_RegisterVariable(&hostname);
2972 Cvar_RegisterVariable(&developer_networking);
2973 Cvar_RegisterVariable(&cl_netport);
2974 Cvar_RegisterVariable(&sv_netport);
2975 Cvar_RegisterVariable(&net_address);
2976 //Cvar_RegisterVariable(&net_address_ipv6);
2977 Cvar_RegisterVariable(&sv_public);
2978 Cvar_RegisterVariable(&sv_heartbeatperiod);
2979 for (i = 0;sv_masters[i].name;i++)
2980 Cvar_RegisterVariable(&sv_masters[i]);
2981 Cvar_RegisterVariable(&gameversion);
2982 // 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.
2983 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2985 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2987 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
2988 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2991 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2993 // 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
2994 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2996 i = atoi(com_argv[i + 1]);
2997 if (i >= 0 && i < 65536)
2999 Con_Printf("-port option used, setting port cvar to %i\n", i);
3000 Cvar_SetValueQuick(&sv_netport, i);
3003 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3007 net_message.data = net_message_buf;
3008 net_message.maxsize = sizeof(net_message_buf);
3009 net_message.cursize = 0;
3013 void NetConn_Shutdown(void)
3015 NetConn_CloseClientPorts();
3016 NetConn_CloseServerPorts();