2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 // for secure rcon authentication
31 #define QWMASTER_PORT 27000
32 #define DPMASTER_PORT 27950
34 // note this defaults on for dedicated servers, off for listen servers
35 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
36 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
38 static cvar_t sv_masters [] =
40 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
41 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
42 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
43 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
44 {0, "sv_masterextra1", "69.59.212.88", "ghdigital.com - default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
45 {0, "sv_masterextra2", "64.22.107.125", "dpmaster.deathmask.net - default master server 2 (admin: Willis)"}, // admin: Willis
46 {0, "sv_masterextra3", "92.62.40.73", "dpmaster.tchr.no - default master server 3 (admin: tChr)"}, // admin: tChr
50 static cvar_t sv_qwmasters [] =
52 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
53 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
54 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
55 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
56 {0, "sv_qwmasterextra1", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
57 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
58 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
59 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
60 {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
64 static double nextheartbeattime = 0;
66 sizebuf_t net_message;
67 static unsigned char net_message_buf[NET_MAXMESSAGE];
69 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
70 cvar_t net_connecttimeout = {0, "net_connecttimeout","15", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods). Must be above 10 seconds."};
71 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
72 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
73 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
75 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
76 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
77 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
78 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
79 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
80 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
81 static cvar_t net_slist_pause = {0, "net_slist_pause", "0", "when set to 1, the server list won't update until it is set back to 0"};
82 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
83 static cvar_t net_slist_favorites = {CVAR_SAVE | CVAR_NQUSERINFOHACK, "net_slist_favorites", "", "contains a list of IP addresses and ports to always query explicitly"};
84 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible"};
85 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode"};
86 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
87 static cvar_t rcon_secure_maxdiff = {0, "rcon_secure_maxdiff", "5", "maximum time difference between rcon request and server system clock (to protect against replay attack)"};
88 extern cvar_t rcon_secure;
90 /* statistic counters */
91 static int packetsSent = 0;
92 static int packetsReSent = 0;
93 static int packetsReceived = 0;
94 static int receivedDuplicateCount = 0;
95 static int droppedDatagrams = 0;
97 static int unreliableMessagesSent = 0;
98 static int unreliableMessagesReceived = 0;
99 static int reliableMessagesSent = 0;
100 static int reliableMessagesReceived = 0;
102 double masterquerytime = -1000;
103 int masterquerycount = 0;
104 int masterreplycount = 0;
105 int serverquerycount = 0;
106 int serverreplycount = 0;
108 // this is only false if there are still servers left to query
109 static qboolean serverlist_querysleep = true;
110 static qboolean serverlist_paused = false;
111 // this is pushed a second or two ahead of realtime whenever a master server
112 // reply is received, to avoid issuing queries while master replies are still
113 // flooding in (which would make a mess of the ping times)
114 static double serverlist_querywaittime = 0;
116 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
117 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
119 static int cl_numsockets;
120 static lhnetsocket_t *cl_sockets[16];
121 static int sv_numsockets;
122 static lhnetsocket_t *sv_sockets[16];
124 netconn_t *netconn_list = NULL;
125 mempool_t *netconn_mempool = NULL;
127 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
128 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
129 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
130 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
132 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
133 int net_extresponse_count = 0;
134 int net_extresponse_last = 0;
136 // ServerList interface
137 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
138 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
140 serverlist_infofield_t serverlist_sortbyfield;
141 int serverlist_sortflags;
143 int serverlist_viewcount = 0;
144 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
146 int serverlist_cachecount;
147 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
149 qboolean serverlist_consoleoutput;
151 static int nFavorites = 0;
152 static lhnetaddress_t favorites[256];
154 void NetConn_UpdateFavorites()
158 p = net_slist_favorites.string;
159 while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
161 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
166 // helper function to insert a value into the viewset
167 // spare entries will be removed
168 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
171 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
172 i = serverlist_viewcount++;
174 i = SERVERLIST_VIEWLISTSIZE - 1;
177 for( ; i > index ; i-- )
178 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
180 serverlist_viewlist[index] = entry;
183 // we suppose serverlist_viewcount to be valid, ie > 0
184 static void _ServerList_ViewList_Helper_Remove( int index )
186 serverlist_viewcount--;
187 for( ; index < serverlist_viewcount ; index++ )
188 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
191 // returns true if A should be inserted before B
192 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
194 int result = 0; // > 0 if for numbers A > B and for text if A < B
196 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
198 if(A->info.isfavorite != B->info.isfavorite)
199 return A->info.isfavorite;
202 switch( serverlist_sortbyfield ) {
204 result = A->info.ping - B->info.ping;
206 case SLIF_MAXPLAYERS:
207 result = A->info.maxplayers - B->info.maxplayers;
209 case SLIF_NUMPLAYERS:
210 result = A->info.numplayers - B->info.numplayers;
213 result = A->info.numbots - B->info.numbots;
216 result = A->info.numhumans - B->info.numhumans;
219 result = A->info.freeslots - B->info.freeslots;
222 result = A->info.protocol - B->info.protocol;
225 result = strcmp( B->info.cname, A->info.cname );
228 result = strcasecmp( B->info.game, A->info.game );
231 result = strcasecmp( B->info.map, A->info.map );
234 result = strcasecmp( B->info.mod, A->info.mod );
237 result = strcasecmp( B->info.name, A->info.name );
240 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
242 case SLIF_ISFAVORITE:
243 result = !!B->info.isfavorite - !!A->info.isfavorite;
246 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
252 if( serverlist_sortflags & SLSF_DESCENDING )
258 // if the chosen sort key is identical, sort by index
259 // (makes this a stable sort, so that later replies from servers won't
260 // shuffle the servers around when they have the same ping)
264 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
266 // This should actually be done with some intermediate and end-of-function return
278 case SLMO_GREATEREQUAL:
280 case SLMO_NOTCONTAIN:
281 case SLMO_STARTSWITH:
282 case SLMO_NOTSTARTSWITH:
285 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
290 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
293 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
294 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
295 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
296 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
298 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
299 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
302 // Same here, also using an intermediate & final return would be more appropriate
306 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
307 case SLMO_NOTCONTAIN:
308 return !*bufferB || !strstr( bufferA, bufferB );
309 case SLMO_STARTSWITH:
310 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
311 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
312 case SLMO_NOTSTARTSWITH:
313 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
315 return strcmp( bufferA, bufferB ) < 0;
317 return strcmp( bufferA, bufferB ) <= 0;
319 return strcmp( bufferA, bufferB ) == 0;
321 return strcmp( bufferA, bufferB ) > 0;
323 return strcmp( bufferA, bufferB ) != 0;
324 case SLMO_GREATEREQUAL:
325 return strcmp( bufferA, bufferB ) >= 0;
327 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
332 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
334 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
336 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
338 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
340 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
342 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
344 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
346 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
348 if( *mask->info.cname
349 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
352 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
355 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
358 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
361 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
363 if( *mask->info.qcstatus
364 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
366 if( *mask->info.players
367 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
369 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
374 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
376 int start, end, mid, i;
379 // reject incompatible servers
380 if (entry->info.gameversion != gameversion.integer)
383 // refresh the "favorite" status
384 entry->info.isfavorite = false;
385 if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
387 for(i = 0; i < nFavorites; ++i)
389 if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
391 entry->info.isfavorite = true;
397 // FIXME: change this to be more readable (...)
398 // now check whether it passes through the masks
399 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
400 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
403 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
404 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
406 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
409 if( !serverlist_viewcount ) {
410 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
413 // ok, insert it, we just need to find out where exactly:
416 // check whether to insert it as new first item
417 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
418 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
420 } // check whether to insert it as new last item
421 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
422 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
426 end = serverlist_viewcount - 1;
427 while( end > start + 1 )
429 mid = (start + end) / 2;
430 // test the item that lies in the middle between start and end
431 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
432 // the item has to be in the upper half
435 // the item has to be in the lower half
438 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
441 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
444 for( i = 0; i < serverlist_viewcount; i++ )
446 if (serverlist_viewlist[i] == entry)
448 _ServerList_ViewList_Helper_Remove(i);
454 void ServerList_RebuildViewList(void)
458 serverlist_viewcount = 0;
459 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
460 serverlist_entry_t *entry = &serverlist_cache[i];
461 // also display entries that are currently being refreshed [11/8/2007 Black]
462 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
463 ServerList_ViewList_Insert( entry );
467 void ServerList_ResetMasks(void)
471 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
472 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
473 // numbots needs to be compared to -1 to always succeed
474 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
475 serverlist_andmasks[i].info.numbots = -1;
476 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
477 serverlist_ormasks[i].info.numbots = -1;
480 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
483 int numplayers = 0, maxplayers = 0;
484 for (i = 0;i < serverlist_cachecount;i++)
486 if (serverlist_cache[i].query == SQS_QUERIED)
488 numplayers += serverlist_cache[i].info.numhumans;
489 maxplayers += serverlist_cache[i].info.maxplayers;
492 *numplayerspointer = numplayers;
493 *maxplayerspointer = maxplayers;
497 static void _ServerList_Test(void)
500 for( i = 0 ; i < 1024 ; i++ ) {
501 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
502 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
503 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
504 serverlist_cache[serverlist_cachecount].finished = true;
505 dpsnprintf( serverlist_cache[serverlist_cachecount].line1, sizeof(serverlist_cache[serverlist_cachecount].info.line1), "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
506 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
507 serverlist_cachecount++;
512 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
514 masterquerytime = realtime;
515 masterquerycount = 0;
516 masterreplycount = 0;
518 serverquerycount = 0;
519 serverreplycount = 0;
520 serverlist_cachecount = 0;
521 serverlist_viewcount = 0;
523 // refresh all entries
525 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
526 serverlist_entry_t *entry = &serverlist_cache[ n ];
527 entry->query = SQS_REFRESHING;
528 entry->querycounter = 0;
531 serverlist_consoleoutput = consoleoutput;
533 //_ServerList_Test();
535 NetConn_QueryMasters(querydp, queryqw);
540 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
542 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
546 if (cl_netpacketloss_receive.integer)
547 for (i = 0;i < cl_numsockets;i++)
548 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
550 if (developer_networking.integer)
552 char addressstring[128], addressstring2[128];
553 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
556 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
557 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
558 Com_HexDumpToConsole((unsigned char *)data, length);
561 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
566 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
570 if (cl_netpacketloss_send.integer)
571 for (i = 0;i < cl_numsockets;i++)
572 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
574 ret = LHNET_Write(mysocket, data, length, peeraddress);
575 if (developer_networking.integer)
577 char addressstring[128], addressstring2[128];
578 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
579 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
580 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
581 Com_HexDumpToConsole((unsigned char *)data, length);
586 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
588 // note this does not include the trailing NULL because we add that in the parser
589 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
592 qboolean NetConn_CanSend(netconn_t *conn)
594 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
595 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
596 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
597 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
598 if (realtime > conn->cleartime)
602 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
607 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
611 // if this packet was supposedly choked, but we find ourselves sending one
612 // anyway, make sure the size counting starts at zero
613 // (this mostly happens on level changes and disconnects and such)
614 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
615 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
617 if (protocol == PROTOCOL_QUAKEWORLD)
620 qboolean sendreliable;
622 // note that it is ok to send empty messages to the qw server,
623 // otherwise it won't respond to us at all
625 sendreliable = false;
626 // if the remote side dropped the last reliable message, resend it
627 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
629 // if the reliable transmit buffer is empty, copy the current message out
630 if (!conn->sendMessageLength && conn->message.cursize)
632 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
633 conn->sendMessageLength = conn->message.cursize;
634 SZ_Clear(&conn->message); // clear the message buffer
635 conn->qw.reliable_sequence ^= 1;
638 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
639 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
640 // last received unreliable packet number, and last received reliable packet number (0 or 1)
641 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
643 conn->outgoing_unreliable_sequence++;
644 // client sends qport in every packet
645 if (conn == cls.netcon)
647 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
649 // also update cls.qw_outgoing_sequence
650 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
652 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
654 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
658 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
660 // add the reliable message if there is one
663 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
664 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
665 packetLen += conn->sendMessageLength;
666 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
669 // add the unreliable message if possible
670 if (packetLen + data->cursize <= 1400)
672 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
673 memcpy(sendbuffer + packetLen, data->data, data->cursize);
674 packetLen += data->cursize;
677 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
680 unreliableMessagesSent++;
682 totallen += packetLen + 28;
686 unsigned int packetLen;
687 unsigned int dataLen;
689 unsigned int *header;
691 // if a reliable message fragment has been lost, send it again
692 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
694 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
696 dataLen = conn->sendMessageLength;
701 dataLen = MAX_PACKETFRAGMENT;
705 packetLen = NET_HEADERSIZE + dataLen;
707 header = (unsigned int *)sendbuffer;
708 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
709 header[1] = BigLong(conn->nq.sendSequence - 1);
710 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
712 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
714 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
716 conn->lastSendTime = realtime;
720 totallen += packetLen + 28;
723 // if we have a new reliable message to send, do so
724 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
726 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
728 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
729 conn->message.overflowed = true;
733 if (developer_networking.integer && conn == cls.netcon)
735 Con_Print("client sending reliable message to server:\n");
736 SZ_HexDumpToConsole(&conn->message);
739 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
740 conn->sendMessageLength = conn->message.cursize;
741 SZ_Clear(&conn->message);
743 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
745 dataLen = conn->sendMessageLength;
750 dataLen = MAX_PACKETFRAGMENT;
754 packetLen = NET_HEADERSIZE + dataLen;
756 header = (unsigned int *)sendbuffer;
757 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
758 header[1] = BigLong(conn->nq.sendSequence);
759 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
761 conn->nq.sendSequence++;
763 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
765 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
767 conn->lastSendTime = realtime;
769 reliableMessagesSent++;
771 totallen += packetLen + 28;
774 // if we have an unreliable message to send, do so
777 packetLen = NET_HEADERSIZE + data->cursize;
779 if (packetLen > (int)sizeof(sendbuffer))
781 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
785 header = (unsigned int *)sendbuffer;
786 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
787 header[1] = BigLong(conn->outgoing_unreliable_sequence);
788 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
790 conn->outgoing_unreliable_sequence++;
792 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
794 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
797 unreliableMessagesSent++;
799 totallen += packetLen + 28;
803 // delay later packets to obey rate limit
804 if (conn->cleartime < realtime - 0.1)
805 conn->cleartime = realtime - 0.1;
806 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
807 if (conn->cleartime < realtime)
808 conn->cleartime = realtime;
813 qboolean NetConn_HaveClientPorts(void)
815 return !!cl_numsockets;
818 qboolean NetConn_HaveServerPorts(void)
820 return !!sv_numsockets;
823 void NetConn_CloseClientPorts(void)
825 for (;cl_numsockets > 0;cl_numsockets--)
826 if (cl_sockets[cl_numsockets - 1])
827 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
830 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
832 lhnetaddress_t address;
834 char addressstring2[1024];
835 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
837 if ((s = LHNET_OpenSocket_Connectionless(&address)))
839 cl_sockets[cl_numsockets++] = s;
840 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
841 Con_Printf("Client opened a socket on address %s\n", addressstring2);
845 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
846 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
850 Con_Printf("Client unable to parse address %s\n", addressstring);
853 void NetConn_OpenClientPorts(void)
856 NetConn_CloseClientPorts();
857 port = bound(0, cl_netport.integer, 65535);
858 if (cl_netport.integer != port)
859 Cvar_SetValueQuick(&cl_netport, port);
861 Con_Printf("Client using an automatically assigned port\n");
863 Con_Printf("Client using port %i\n", port);
864 NetConn_OpenClientPort("local:2", 0);
865 NetConn_OpenClientPort(net_address.string, port);
866 NetConn_OpenClientPort(net_address_ipv6.string, port);
869 void NetConn_CloseServerPorts(void)
871 for (;sv_numsockets > 0;sv_numsockets--)
872 if (sv_sockets[sv_numsockets - 1])
873 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
876 qboolean NetConn_OpenServerPort(const char *addressstring, int defaultport, int range)
878 lhnetaddress_t address;
881 char addressstring2[1024];
883 for (port = defaultport; port <= defaultport + range; port++)
885 if (LHNETADDRESS_FromString(&address, addressstring, port))
887 if ((s = LHNET_OpenSocket_Connectionless(&address)))
889 sv_sockets[sv_numsockets++] = s;
890 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
891 Con_Printf("Server listening on address %s\n", addressstring2);
896 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
897 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
902 Con_Printf("Server unable to parse address %s\n", addressstring);
903 // if it cant parse one address, it wont be able to parse another for sure
910 void NetConn_OpenServerPorts(int opennetports)
913 NetConn_CloseServerPorts();
914 NetConn_UpdateSockets();
915 port = bound(0, sv_netport.integer, 65535);
918 Con_Printf("Server using port %i\n", port);
919 if (sv_netport.integer != port)
920 Cvar_SetValueQuick(&sv_netport, port);
921 if (cls.state != ca_dedicated)
922 NetConn_OpenServerPort("local:1", 0, 1);
925 qboolean ip4success = NetConn_OpenServerPort(net_address.string, port, 100);
926 NetConn_OpenServerPort(net_address_ipv6.string, port, ip4success ? 1 : 100);
928 if (sv_numsockets == 0)
929 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
932 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
934 int i, a = LHNETADDRESS_GetAddressType(address);
935 for (i = 0;i < cl_numsockets;i++)
936 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
937 return cl_sockets[i];
941 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
943 int i, a = LHNETADDRESS_GetAddressType(address);
944 for (i = 0;i < sv_numsockets;i++)
945 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
946 return sv_sockets[i];
950 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
953 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
954 conn->mysocket = mysocket;
955 conn->peeraddress = *peeraddress;
956 conn->lastMessageTime = realtime;
957 conn->message.data = conn->messagedata;
958 conn->message.maxsize = sizeof(conn->messagedata);
959 conn->message.cursize = 0;
960 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
961 // reduce effectiveness of connection request floods
962 conn->timeout = realtime + net_connecttimeout.value;
963 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
964 conn->next = netconn_list;
969 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
970 void NetConn_Close(netconn_t *conn)
973 // remove connection from list
975 // allow the client to reconnect immediately
976 NetConn_ClearConnectFlood(&(conn->peeraddress));
978 if (conn == netconn_list)
979 netconn_list = conn->next;
982 for (c = netconn_list;c;c = c->next)
986 c->next = conn->next;
990 // not found in list, we'll avoid crashing here...
998 static int clientport = -1;
999 static int clientport2 = -1;
1000 static int hostport = -1;
1001 void NetConn_UpdateSockets(void)
1003 if (cls.state != ca_dedicated)
1005 if (clientport2 != cl_netport.integer)
1007 clientport2 = cl_netport.integer;
1008 if (cls.state == ca_connected)
1009 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1011 if (cls.state == ca_disconnected && clientport != clientport2)
1013 clientport = clientport2;
1014 NetConn_CloseClientPorts();
1016 if (cl_numsockets == 0)
1017 NetConn_OpenClientPorts();
1020 if (hostport != sv_netport.integer)
1022 hostport = sv_netport.integer;
1024 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1028 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1030 int originallength = length;
1034 if (protocol == PROTOCOL_QUAKEWORLD)
1036 int sequence, sequence_ack;
1037 int reliable_ack, reliable_message;
1041 sequence = LittleLong(*((int *)(data + 0)));
1042 sequence_ack = LittleLong(*((int *)(data + 4)));
1046 if (conn != cls.netcon)
1051 // 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?)
1052 qport = LittleShort(*((int *)(data + 8)));
1058 reliable_message = (sequence >> 31) & 1;
1059 reliable_ack = (sequence_ack >> 31) & 1;
1060 sequence &= ~(1<<31);
1061 sequence_ack &= ~(1<<31);
1062 if (sequence <= conn->qw.incoming_sequence)
1064 //Con_DPrint("Got a stale datagram\n");
1067 count = sequence - (conn->qw.incoming_sequence + 1);
1070 droppedDatagrams += count;
1071 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1074 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1075 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1076 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1077 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1080 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1081 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1082 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1083 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1084 if (reliable_ack == conn->qw.reliable_sequence)
1086 // received, now we will be able to send another reliable message
1087 conn->sendMessageLength = 0;
1088 reliableMessagesReceived++;
1090 conn->qw.incoming_sequence = sequence;
1091 if (conn == cls.netcon)
1092 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1093 conn->qw.incoming_acknowledged = sequence_ack;
1094 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1095 if (reliable_message)
1096 conn->qw.incoming_reliable_sequence ^= 1;
1097 conn->lastMessageTime = realtime;
1098 conn->timeout = realtime + newtimeout;
1099 unreliableMessagesReceived++;
1100 SZ_Clear(&net_message);
1101 SZ_Write(&net_message, data, length);
1109 unsigned int sequence;
1112 qlength = (unsigned int)BigLong(((int *)data)[0]);
1113 flags = qlength & ~NETFLAG_LENGTH_MASK;
1114 qlength &= NETFLAG_LENGTH_MASK;
1115 // control packets were already handled
1116 if (!(flags & NETFLAG_CTL) && qlength == length)
1118 sequence = BigLong(((int *)data)[1]);
1122 if (flags & NETFLAG_UNRELIABLE)
1124 if (sequence >= conn->nq.unreliableReceiveSequence)
1126 if (sequence > conn->nq.unreliableReceiveSequence)
1128 count = sequence - conn->nq.unreliableReceiveSequence;
1129 droppedDatagrams += count;
1130 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1133 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1134 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1135 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1136 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1139 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1140 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1141 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1142 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1143 conn->nq.unreliableReceiveSequence = sequence + 1;
1144 conn->lastMessageTime = realtime;
1145 conn->timeout = realtime + newtimeout;
1146 unreliableMessagesReceived++;
1149 SZ_Clear(&net_message);
1150 SZ_Write(&net_message, data, length);
1156 // Con_DPrint("Got a stale datagram\n");
1159 else if (flags & NETFLAG_ACK)
1161 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1162 if (sequence == (conn->nq.sendSequence - 1))
1164 if (sequence == conn->nq.ackSequence)
1166 conn->nq.ackSequence++;
1167 if (conn->nq.ackSequence != conn->nq.sendSequence)
1168 Con_DPrint("ack sequencing error\n");
1169 conn->lastMessageTime = realtime;
1170 conn->timeout = realtime + newtimeout;
1171 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1173 unsigned int packetLen;
1174 unsigned int dataLen;
1176 unsigned int *header;
1178 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1179 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1181 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1183 dataLen = conn->sendMessageLength;
1188 dataLen = MAX_PACKETFRAGMENT;
1192 packetLen = NET_HEADERSIZE + dataLen;
1194 header = (unsigned int *)sendbuffer;
1195 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1196 header[1] = BigLong(conn->nq.sendSequence);
1197 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1199 conn->nq.sendSequence++;
1201 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1203 conn->lastSendTime = realtime;
1208 conn->sendMessageLength = 0;
1211 // Con_DPrint("Duplicate ACK received\n");
1214 // Con_DPrint("Stale ACK received\n");
1217 else if (flags & NETFLAG_DATA)
1219 unsigned int temppacket[2];
1220 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1221 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1222 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1223 temppacket[1] = BigLong(sequence);
1224 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1225 if (sequence == conn->nq.receiveSequence)
1227 conn->lastMessageTime = realtime;
1228 conn->timeout = realtime + newtimeout;
1229 conn->nq.receiveSequence++;
1230 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1231 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1232 conn->receiveMessageLength += length;
1234 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1235 "Dropping the message!\n", sequence );
1236 conn->receiveMessageLength = 0;
1239 if (flags & NETFLAG_EOM)
1241 reliableMessagesReceived++;
1242 length = conn->receiveMessageLength;
1243 conn->receiveMessageLength = 0;
1246 SZ_Clear(&net_message);
1247 SZ_Write(&net_message, conn->receiveMessage, length);
1254 receivedDuplicateCount++;
1262 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1264 cls.connect_trying = false;
1265 M_Update_Return_Reason("");
1266 // the connection request succeeded, stop current connection and set up a new connection
1268 // if we're connecting to a remote server, shut down any local server
1269 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1270 Host_ShutdownServer ();
1271 // allocate a net connection to keep track of things
1272 cls.netcon = NetConn_Open(mysocket, peeraddress);
1273 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1274 key_dest = key_game;
1276 cls.demonum = -1; // not in the demo loop now
1277 cls.state = ca_connected;
1278 cls.signon = 0; // need all the signon messages before playing
1279 cls.protocol = initialprotocol;
1280 // reset move sequence numbering on this new connection
1281 cls.servermovesequence = 0;
1282 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1283 Cmd_ForwardStringToServer("new");
1284 if (cls.protocol == PROTOCOL_QUAKE)
1286 // write a keepalive (clc_nop) as it seems to greatly improve the
1287 // chances of connecting to a netquake server
1289 unsigned char buf[4];
1290 memset(&msg, 0, sizeof(msg));
1292 msg.maxsize = sizeof(buf);
1293 MSG_WriteChar(&msg, clc_nop);
1294 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1298 int NetConn_IsLocalGame(void)
1300 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1305 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1309 serverlist_entry_t *entry = NULL;
1311 // search the cache for this server and update it
1312 for (n = 0;n < serverlist_cachecount;n++) {
1313 entry = &serverlist_cache[ n ];
1314 if (!strcmp(addressstring, entry->info.cname))
1318 if (n == serverlist_cachecount)
1320 // LAN search doesnt require an answer from the master server so we wont
1321 // know the ping nor will it be initialized already...
1324 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1327 entry = &serverlist_cache[n];
1329 memset(entry, 0, sizeof(*entry));
1330 // store the data the engine cares about (address and ping)
1331 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1332 entry->info.ping = 100000;
1333 entry->querytime = realtime;
1334 // if not in the slist menu we should print the server to console
1335 if (serverlist_consoleoutput)
1336 Con_Printf("querying %s\n", addressstring);
1337 ++serverlist_cachecount;
1339 // if this is the first reply from this server, count it as having replied
1340 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1341 pingtime = bound(0, pingtime, 9999);
1342 if (entry->query == SQS_REFRESHING) {
1343 entry->info.ping = pingtime;
1344 entry->query = SQS_QUERIED;
1346 // convert to unsigned to catch the -1
1347 // 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]
1348 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1352 // other server info is updated by the caller
1356 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1358 serverlist_entry_t *entry = &serverlist_cache[n];
1359 serverlist_info_t *info = &entry->info;
1360 // update description strings for engine menu and console output
1361 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);
1362 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);
1363 if (entry->query == SQS_QUERIED)
1365 if(!serverlist_paused)
1366 ServerList_ViewList_Remove(entry);
1368 // if not in the slist menu we should print the server to console (if wanted)
1369 else if( serverlist_consoleoutput )
1370 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1371 // and finally, update the view set
1372 if(!serverlist_paused)
1373 ServerList_ViewList_Insert( entry );
1374 // update the entry's state
1375 serverlist_cache[n].query = SQS_QUERIED;
1378 // returns true, if it's sensible to continue the processing
1379 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1381 serverlist_entry_t *entry;
1383 // ignore the rest of the message if the serverlist is full
1384 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1386 // also ignore it if we have already queried it (other master server response)
1387 for( n = 0 ; n < serverlist_cachecount ; n++ )
1388 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1391 entry = &serverlist_cache[n];
1393 if( n < serverlist_cachecount ) {
1394 // the entry has already been queried once or
1398 memset(entry, 0, sizeof(entry));
1399 entry->protocol = protocol;
1400 // store the data the engine cares about (address and ping)
1401 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1403 entry->info.isfavorite = isfavorite;
1405 // no, then reset the ping right away
1406 entry->info.ping = -1;
1407 // we also want to increase the serverlist_cachecount then
1408 serverlist_cachecount++;
1411 entry->query = SQS_QUERYING;
1416 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1419 if (serverlist_consoleoutput)
1420 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1423 char ipstring [128];
1426 if (data[0] == '\\')
1428 unsigned short port = data[5] * 256 + data[6];
1430 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1431 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1433 // move on to next address in packet
1438 else if (data[0] == '/' && isextended && length >= 19)
1440 unsigned short port = data[17] * 256 + data[18];
1446 // TODO: make some basic checks of the IP address (broadcast, ...)
1448 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1451 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1452 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1453 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1458 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1459 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1460 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1465 // move on to next address in packet
1471 Con_Print("Error while parsing the server list\n");
1475 if (serverlist_consoleoutput && developer_networking.integer)
1476 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1478 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1484 // begin or resume serverlist queries
1485 serverlist_querysleep = false;
1486 serverlist_querywaittime = realtime + 3;
1489 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1491 qboolean fromserver;
1492 int ret, c, control;
1494 char *string, addressstring2[128], ipstring[32];
1495 char stringbuf[16384];
1497 // quakeworld ingame packet
1498 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1500 // convert the address to a string incase we need it
1501 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1503 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1505 // received a command string - strip off the packaging and put it
1506 // into our string buffer with NULL termination
1509 length = min(length, (int)sizeof(stringbuf) - 1);
1510 memcpy(stringbuf, data, length);
1511 stringbuf[length] = 0;
1514 if (developer_networking.integer)
1516 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1517 Com_HexDumpToConsole(data, length);
1520 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1522 // darkplaces or quake3
1523 char protocolnames[1400];
1524 Protocol_Names(protocolnames, sizeof(protocolnames));
1525 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1526 M_Update_Return_Reason("Got challenge response");
1527 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1528 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1529 // TODO: add userinfo stuff here instead of using NQ commands?
1530 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1533 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1535 // darkplaces or quake3
1536 M_Update_Return_Reason("Accepted");
1537 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1540 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1542 char rejectreason[32];
1543 cls.connect_trying = false;
1545 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1546 memcpy(rejectreason, string, length);
1547 rejectreason[length] = 0;
1548 M_Update_Return_Reason(rejectreason);
1551 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1553 serverlist_info_t *info;
1558 // search the cache for this server and update it
1559 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1563 info = &serverlist_cache[n].info;
1568 info->qcstatus[0] = 0;
1569 info->players[0] = 0;
1570 info->protocol = -1;
1571 info->numplayers = 0;
1573 info->maxplayers = 0;
1574 info->gameversion = 0;
1576 p = strchr(string, '\n');
1579 *p = 0; // cut off the string there
1583 Con_Printf("statusResponse without players block?\n");
1585 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1586 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1587 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1588 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1589 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1590 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1591 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1592 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1593 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1594 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1595 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1596 info->numhumans = info->numplayers - max(0, info->numbots);
1597 info->freeslots = info->maxplayers - info->numplayers;
1599 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1603 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1605 serverlist_info_t *info;
1609 // search the cache for this server and update it
1610 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1614 info = &serverlist_cache[n].info;
1619 info->qcstatus[0] = 0;
1620 info->players[0] = 0;
1621 info->protocol = -1;
1622 info->numplayers = 0;
1624 info->maxplayers = 0;
1625 info->gameversion = 0;
1627 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1628 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1629 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1630 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1631 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1632 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1633 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1634 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1635 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1636 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1637 info->numhumans = info->numplayers - max(0, info->numbots);
1638 info->freeslots = info->maxplayers - info->numplayers;
1640 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1644 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1646 // Extract the IP addresses
1649 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1652 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1654 // Extract the IP addresses
1657 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1660 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1662 // Extract the IP addresses
1666 if (serverlist_consoleoutput)
1667 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1668 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1670 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1671 if (serverlist_consoleoutput && developer_networking.integer)
1672 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1674 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1678 // move on to next address in packet
1682 // begin or resume serverlist queries
1683 serverlist_querysleep = false;
1684 serverlist_querywaittime = realtime + 3;
1687 if (!strncmp(string, "extResponse ", 12))
1689 ++net_extresponse_count;
1690 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1691 net_extresponse_count = NET_EXTRESPONSE_MAX;
1692 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1693 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1696 if (!strncmp(string, "ping", 4))
1698 if (developer.integer >= 10)
1699 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1700 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1703 if (!strncmp(string, "ack", 3))
1705 // QuakeWorld compatibility
1706 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1708 // challenge message
1709 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1710 M_Update_Return_Reason("Got QuakeWorld challenge response");
1711 cls.qw_qport = qport.integer;
1712 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1713 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1714 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1717 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1720 M_Update_Return_Reason("QuakeWorld Accepted");
1721 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1724 if (length > 2 && !memcmp(string, "n\\", 2))
1726 serverlist_info_t *info;
1730 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1731 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1734 // search the cache for this server and update it
1735 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1739 info = &serverlist_cache[n].info;
1740 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1741 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1742 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1743 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1745 info->numplayers = 0; // updated below
1746 info->numhumans = 0; // updated below
1747 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1748 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1750 // count active players on server
1751 // (we could gather more info, but we're just after the number)
1752 s = strchr(string, '\n');
1756 while (s < string + length)
1758 for (;s < string + length && *s != '\n';s++)
1760 if (s >= string + length)
1768 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1772 if (string[0] == 'n')
1775 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1777 // we may not have liked the packet, but it was a command packet, so
1778 // we're done processing this packet now
1781 // quakeworld ingame packet
1782 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1785 CL_ParseServerMessage();
1788 // netquake control packets, supported for compatibility only
1789 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1792 serverlist_info_t *info;
1796 SZ_Clear(&net_message);
1797 SZ_Write(&net_message, data, length);
1803 if (developer.integer >= 10)
1804 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1805 if (cls.connect_trying)
1807 lhnetaddress_t clientportaddress;
1808 clientportaddress = *peeraddress;
1809 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1810 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1811 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1812 M_Update_Return_Reason("Accepted");
1813 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1817 if (developer.integer >= 10)
1818 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1819 cls.connect_trying = false;
1820 M_Update_Return_Reason((char *)MSG_ReadString());
1822 case CCREP_SERVER_INFO:
1823 if (developer.integer >= 10)
1824 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1825 // LordHavoc: because the quake server may report weird addresses
1826 // we just ignore it and keep the real address
1828 // search the cache for this server and update it
1829 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1833 info = &serverlist_cache[n].info;
1834 strlcpy(info->game, "Quake", sizeof(info->game));
1835 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1836 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1837 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1838 info->numplayers = MSG_ReadByte();
1839 info->maxplayers = MSG_ReadByte();
1840 info->protocol = MSG_ReadByte();
1842 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1845 case CCREP_PLAYER_INFO:
1846 // we got a CCREP_PLAYER_INFO??
1847 //if (developer.integer >= 10)
1848 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1850 case CCREP_RULE_INFO:
1851 // we got a CCREP_RULE_INFO??
1852 //if (developer.integer >= 10)
1853 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1858 SZ_Clear(&net_message);
1859 // we may not have liked the packet, but it was a valid control
1860 // packet, so we're done processing this packet now
1864 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1865 CL_ParseServerMessage();
1869 void NetConn_QueryQueueFrame(void)
1875 static double querycounter = 0;
1877 if(!net_slist_pause.integer && serverlist_paused)
1878 ServerList_RebuildViewList();
1879 serverlist_paused = net_slist_pause.integer;
1881 if (serverlist_querysleep)
1884 // apply a cool down time after master server replies,
1885 // to avoid messing up the ping times on the servers
1886 if (serverlist_querywaittime > realtime)
1889 // each time querycounter reaches 1.0 issue a query
1890 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1891 maxqueries = (int)querycounter;
1892 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1893 querycounter -= maxqueries;
1895 if( maxqueries == 0 ) {
1899 // scan serverlist and issue queries as needed
1900 serverlist_querysleep = true;
1902 timeouttime = realtime - net_slist_timeout.value;
1903 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1905 serverlist_entry_t *entry = &serverlist_cache[ index ];
1906 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1911 serverlist_querysleep = false;
1912 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1917 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1919 lhnetaddress_t address;
1922 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1923 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1925 for (socket = 0; socket < cl_numsockets ; socket++)
1926 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1930 for (socket = 0; socket < cl_numsockets ; socket++)
1931 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1934 // update the entry fields
1935 entry->querytime = realtime;
1936 entry->querycounter++;
1938 // if not in the slist menu we should print the server to console
1939 if (serverlist_consoleoutput)
1940 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1946 // have we tried to refresh this server?
1947 if( entry->query == SQS_REFRESHING ) {
1948 // yes, so update the reply count (since its not responding anymore)
1950 if(!serverlist_paused)
1951 ServerList_ViewList_Remove(entry);
1953 entry->query = SQS_TIMEDOUT;
1958 void NetConn_ClientFrame(void)
1961 lhnetaddress_t peeraddress;
1962 NetConn_UpdateSockets();
1963 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1965 if (cls.connect_remainingtries == 0)
1966 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1967 cls.connect_nextsendtime = realtime + 1;
1968 cls.connect_remainingtries--;
1969 if (cls.connect_remainingtries <= -10)
1971 cls.connect_trying = false;
1972 M_Update_Return_Reason("Connect: Failed");
1975 // try challenge first (newer DP server or QW)
1976 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1977 // then try netquake as a fallback (old server, or netquake)
1978 SZ_Clear(&net_message);
1979 // save space for the header, filled in later
1980 MSG_WriteLong(&net_message, 0);
1981 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1982 MSG_WriteString(&net_message, "QUAKE");
1983 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1984 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1985 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1986 SZ_Clear(&net_message);
1988 for (i = 0;i < cl_numsockets;i++)
1989 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1990 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1991 NetConn_QueryQueueFrame();
1992 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1994 Con_Print("Connection timed out\n");
1996 Host_ShutdownServer ();
2000 #define MAX_CHALLENGES 128
2003 lhnetaddress_t address;
2007 challenge[MAX_CHALLENGES];
2009 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2013 for (i = 0;i < bufferlength - 1;i++)
2017 c = rand () % (127 - 33) + 33;
2018 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2024 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2025 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2028 unsigned int nb_clients = 0, nb_bots = 0, i;
2034 // How many clients are there?
2035 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2037 if (svs.clients[i].active)
2040 if (!svs.clients[i].netconnection)
2046 if(prog->globaloffsets.worldstatus >= 0)
2048 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2054 for(q = str; *q; ++q)
2055 if(*q != '\\' && *q != '\n')
2061 // TODO: we should add more information for the full status string
2062 length = dpsnprintf(out_msg, out_size,
2063 "\377\377\377\377%s\x0A"
2064 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2065 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2069 fullstatus ? "statusResponse" : "infoResponse",
2070 gamename, com_modname, gameversion.integer, svs.maxclients,
2071 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2072 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2073 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2074 fullstatus ? "\n" : "");
2076 // Make sure it fits in the buffer
2086 savelength = length;
2088 ptr = out_msg + length;
2089 left = (int)out_size - length;
2091 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2093 client_t *cl = &svs.clients[i];
2096 int nameind, cleanind, pingvalue;
2098 char cleanname [sizeof(cl->name)];
2100 // Remove all characters '"' and '\' in the player name
2105 curchar = cl->name[nameind++];
2106 if (curchar != '"' && curchar != '\\')
2108 cleanname[cleanind++] = curchar;
2109 if (cleanind == sizeof(cleanname) - 1)
2112 } while (curchar != '\0');
2113 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2115 pingvalue = (int)(cl->ping * 1000.0f);
2116 if(cl->netconnection)
2117 pingvalue = bound(1, pingvalue, 9999);
2122 if(prog->fieldoffsets.clientstatus >= 0)
2124 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2130 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2131 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2137 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2139 if(cl->frags == -666) // spectator
2140 strlcpy(teambuf, " 0", sizeof(teambuf));
2141 else if(cl->colors == 0x44) // red team
2142 strlcpy(teambuf, " 1", sizeof(teambuf));
2143 else if(cl->colors == 0xDD) // blue team
2144 strlcpy(teambuf, " 2", sizeof(teambuf));
2145 else if(cl->colors == 0xCC) // yellow team
2146 strlcpy(teambuf, " 3", sizeof(teambuf));
2147 else if(cl->colors == 0x99) // pink team
2148 strlcpy(teambuf, " 4", sizeof(teambuf));
2150 strlcpy(teambuf, " 0", sizeof(teambuf));
2155 // note: team number is inserted according to SoF2 protocol
2157 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2163 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2172 // turn it into an infoResponse!
2173 out_msg[savelength] = 0;
2174 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2175 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2192 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2194 int floodslotnum, bestfloodslotnum;
2195 double bestfloodtime;
2196 lhnetaddress_t noportpeeraddress;
2197 // see if this is a connect flood
2198 noportpeeraddress = *peeraddress;
2199 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2200 bestfloodslotnum = 0;
2201 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2202 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2204 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2206 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2207 bestfloodslotnum = floodslotnum;
2209 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2211 // this address matches an ongoing flood address
2212 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2214 // renew the ban on this address so it does not expire
2215 // until the flood has subsided
2216 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2217 //Con_Printf("Flood detected!\n");
2220 // the flood appears to have subsided, so allow this
2221 bestfloodslotnum = floodslotnum; // reuse the same slot
2225 // begin a new timeout on this address
2226 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2227 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2228 //Con_Printf("Flood detection initiated!\n");
2232 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2235 lhnetaddress_t noportpeeraddress;
2236 // see if this is a connect flood
2237 noportpeeraddress = *peeraddress;
2238 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2239 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2241 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2243 // this address matches an ongoing flood address
2245 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2246 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2247 //Con_Printf("Flood cleared!\n");
2252 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2254 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2259 t1 = (long) time(NULL);
2260 t2 = strtol(s, NULL, 0);
2261 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2264 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2267 return !memcmp(mdfourbuf, hash, 16);
2270 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2272 return !strcmp(password, hash);
2275 // returns a string describing the user level, or NULL for auth failure
2276 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2281 if(comparator(rcon_password.string, password, cs, cslen))
2284 if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2287 for(text = s; text != endpos; ++text)
2288 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2289 return NULL; // block possible exploits against the parser/alias expansion
2293 size_t l = strlen(s);
2296 hasquotes = (strchr(s, '"') != NULL);
2297 // sorry, we can't allow these substrings in wildcard expressions,
2298 // as they can mess with the argument counts
2299 text = rcon_restricted_commands.string;
2300 while(COM_ParseToken_Console(&text))
2302 // com_token now contains a pattern to check for...
2303 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2306 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2309 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2311 if(!strcmp(com_token, s))
2314 else // single-arg expression? must match the beginning of the command
2316 if(!strcmp(com_token, s))
2318 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2322 // if we got here, nothing matched!
2329 return "restricted rcon";
2332 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2336 // looks like a legitimate rcon command with the correct password
2337 const char *s_ptr = s;
2338 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2339 while(s_ptr != endpos)
2341 size_t l = strlen(s_ptr);
2343 Con_Printf(" %s;", s_ptr);
2348 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2349 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2352 size_t l = strlen(s);
2355 client_t *host_client_save = host_client;
2356 Cmd_ExecuteString(s, src_command);
2357 host_client = host_client_save;
2358 // in case it is a command that changes host_client (like restart)
2362 Con_Rcon_Redirect_End();
2366 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2370 extern void SV_SendServerinfo (client_t *client);
2371 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2373 int i, ret, clientnum, best;
2376 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2377 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2382 // convert the address to a string incase we need it
2383 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2385 // see if we can identify the sender as a local player
2386 // (this is necessary for rcon to send a reliable reply if the client is
2387 // actually on the server, not sending remotely)
2388 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2389 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2391 if (i == svs.maxclients)
2394 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2396 // received a command string - strip off the packaging and put it
2397 // into our string buffer with NULL termination
2400 length = min(length, (int)sizeof(stringbuf) - 1);
2401 memcpy(stringbuf, data, length);
2402 stringbuf[length] = 0;
2405 if (developer.integer >= 10)
2407 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2408 Com_HexDumpToConsole(data, length);
2411 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2413 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2415 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2417 if (besttime > challenge[i].time)
2418 besttime = challenge[best = i].time;
2420 // if we did not find an exact match, choose the oldest and
2421 // update address and string
2422 if (i == MAX_CHALLENGES)
2425 challenge[i].address = *peeraddress;
2426 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2428 challenge[i].time = realtime;
2429 // send the challenge
2430 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2433 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2438 if (!(s = SearchInfostring(string, "challenge")))
2440 // validate the challenge
2441 for (i = 0;i < MAX_CHALLENGES;i++)
2442 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2444 // if the challenge is not recognized, drop the packet
2445 if (i == MAX_CHALLENGES)
2448 // check engine protocol
2449 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2451 if (developer.integer >= 10)
2452 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2453 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2457 // see if this is a duplicate connection request or a disconnected
2458 // client who is rejoining to the same client slot
2459 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2461 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2463 // this is a known client...
2464 if (client->spawned)
2466 // client crashed and is coming back,
2467 // keep their stuff intact
2468 if (developer.integer >= 10)
2469 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2470 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2472 SV_SendServerinfo(client);
2477 // client is still trying to connect,
2478 // so we send a duplicate reply
2479 if (developer.integer >= 10)
2480 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2481 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2487 if (NetConn_PreventConnectFlood(peeraddress))
2490 // find an empty client slot for this new client
2491 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2494 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2496 // allocated connection
2497 if (developer.integer >= 10)
2498 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2499 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2500 // now set up the client
2502 SV_ConnectClient(clientnum, conn);
2504 NetConn_Heartbeat(1);
2509 // no empty slots found - server is full
2510 if (developer.integer >= 10)
2511 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2512 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2516 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2518 const char *challenge = NULL;
2520 // If there was a challenge in the getinfo message
2521 if (length > 8 && string[7] == ' ')
2522 challenge = string + 8;
2524 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2526 if (developer.integer >= 10)
2527 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2528 NetConn_WriteString(mysocket, response, peeraddress);
2532 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2534 const char *challenge = NULL;
2536 // If there was a challenge in the getinfo message
2537 if (length > 10 && string[9] == ' ')
2538 challenge = string + 10;
2540 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2542 if (developer.integer >= 10)
2543 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2544 NetConn_WriteString(mysocket, response, peeraddress);
2548 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2550 char *password = string + 20;
2551 char *timeval = string + 37;
2552 char *s = strchr(timeval, ' ');
2553 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2554 const char *userlevel;
2556 return true; // invalid packet
2559 userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2560 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2563 if (length >= 5 && !memcmp(string, "rcon ", 5))
2566 char *s = string + 5;
2567 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2570 if(rcon_secure.integer)
2573 for (i = 0;!ISWHITESPACE(*s);s++)
2574 if (i < (int)sizeof(password) - 1)
2576 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2579 if (!ISWHITESPACE(password[0]))
2581 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2582 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2586 if (!strncmp(string, "ping", 4))
2588 if (developer.integer >= 10)
2589 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2590 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2593 if (!strncmp(string, "ack", 3))
2595 // we may not have liked the packet, but it was a command packet, so
2596 // we're done processing this packet now
2599 // netquake control packets, supported for compatibility only, and only
2600 // when running game protocols that are normally served via this connection
2602 // (this protects more modern protocols against being used for
2603 // Quake packet flood Denial Of Service attacks)
2604 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))
2608 const char *protocolname;
2611 SZ_Clear(&net_message);
2612 SZ_Write(&net_message, data, length);
2618 if (developer.integer >= 10)
2619 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2620 if(!islocal && sv_public.integer <= -2)
2623 protocolname = MSG_ReadString();
2624 protocolnumber = MSG_ReadByte();
2625 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2627 if (developer.integer >= 10)
2628 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2629 SZ_Clear(&net_message);
2630 // save space for the header, filled in later
2631 MSG_WriteLong(&net_message, 0);
2632 MSG_WriteByte(&net_message, CCREP_REJECT);
2633 MSG_WriteString(&net_message, "Incompatible version.\n");
2634 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2635 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2636 SZ_Clear(&net_message);
2640 // see if this connect request comes from a known client
2641 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2643 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2645 // this is either a duplicate connection request
2646 // or coming back from a timeout
2647 // (if so, keep their stuff intact)
2650 if (developer.integer >= 10)
2651 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2652 SZ_Clear(&net_message);
2653 // save space for the header, filled in later
2654 MSG_WriteLong(&net_message, 0);
2655 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2656 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2657 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2658 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2659 SZ_Clear(&net_message);
2661 // if client is already spawned, re-send the
2662 // serverinfo message as they'll need it to play
2663 if (client->spawned)
2666 SV_SendServerinfo(client);
2673 // this is a new client, check for connection flood
2674 if (NetConn_PreventConnectFlood(peeraddress))
2677 // find a slot for the new client
2678 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2681 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2683 // connect to the client
2684 // everything is allocated, just fill in the details
2685 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2686 if (developer.integer >= 10)
2687 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2688 // send back the info about the server connection
2689 SZ_Clear(&net_message);
2690 // save space for the header, filled in later
2691 MSG_WriteLong(&net_message, 0);
2692 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2693 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2694 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2695 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2696 SZ_Clear(&net_message);
2697 // now set up the client struct
2699 SV_ConnectClient(clientnum, conn);
2701 NetConn_Heartbeat(1);
2706 if (developer.integer >= 10)
2707 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2708 // no room; try to let player know
2709 SZ_Clear(&net_message);
2710 // save space for the header, filled in later
2711 MSG_WriteLong(&net_message, 0);
2712 MSG_WriteByte(&net_message, CCREP_REJECT);
2713 MSG_WriteString(&net_message, "Server is full.\n");
2714 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2715 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2716 SZ_Clear(&net_message);
2718 case CCREQ_SERVER_INFO:
2719 if (developer.integer >= 10)
2720 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2721 if(!islocal && sv_public.integer <= -1)
2723 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2726 char myaddressstring[128];
2727 if (developer.integer >= 10)
2728 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2729 SZ_Clear(&net_message);
2730 // save space for the header, filled in later
2731 MSG_WriteLong(&net_message, 0);
2732 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2733 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2734 MSG_WriteString(&net_message, myaddressstring);
2735 MSG_WriteString(&net_message, hostname.string);
2736 MSG_WriteString(&net_message, sv.name);
2737 // How many clients are there?
2738 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2739 if (svs.clients[i].active)
2741 MSG_WriteByte(&net_message, numclients);
2742 MSG_WriteByte(&net_message, svs.maxclients);
2743 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2744 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2745 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2746 SZ_Clear(&net_message);
2749 case CCREQ_PLAYER_INFO:
2750 if (developer.integer >= 10)
2751 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2752 if(!islocal && sv_public.integer <= -1)
2756 int playerNumber, activeNumber, clientNumber;
2759 playerNumber = MSG_ReadByte();
2761 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2762 if (client->active && ++activeNumber == playerNumber)
2764 if (clientNumber != svs.maxclients)
2766 SZ_Clear(&net_message);
2767 // save space for the header, filled in later
2768 MSG_WriteLong(&net_message, 0);
2769 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2770 MSG_WriteByte(&net_message, playerNumber);
2771 MSG_WriteString(&net_message, client->name);
2772 MSG_WriteLong(&net_message, client->colors);
2773 MSG_WriteLong(&net_message, client->frags);
2774 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2775 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2776 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2777 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2778 SZ_Clear(&net_message);
2782 case CCREQ_RULE_INFO:
2783 if (developer.integer >= 10)
2784 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2785 if(!islocal && sv_public.integer <= -1)
2792 // find the search start location
2793 prevCvarName = MSG_ReadString();
2794 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2796 // send the response
2797 SZ_Clear(&net_message);
2798 // save space for the header, filled in later
2799 MSG_WriteLong(&net_message, 0);
2800 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2803 MSG_WriteString(&net_message, var->name);
2804 MSG_WriteString(&net_message, var->string);
2806 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2807 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2808 SZ_Clear(&net_message);
2814 SZ_Clear(&net_message);
2815 // we may not have liked the packet, but it was a valid control
2816 // packet, so we're done processing this packet now
2821 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2824 SV_ReadClientMessage();
2832 void NetConn_ServerFrame(void)
2835 lhnetaddress_t peeraddress;
2836 for (i = 0;i < sv_numsockets;i++)
2837 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2838 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2839 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2841 // never timeout loopback connections
2842 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2844 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2846 SV_DropClient(false);
2852 void NetConn_SleepMicroseconds(int microseconds)
2854 LHNET_SleepUntilPacket_Microseconds(microseconds);
2857 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2861 lhnetaddress_t masteraddress;
2862 lhnetaddress_t broadcastaddress;
2865 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2868 // 26000 is the default quake server port, servers on other ports will not
2870 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2871 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2875 for (i = 0;i < cl_numsockets;i++)
2879 const char *cmdname, *extraoptions;
2880 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2882 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2884 // search LAN for Quake servers
2885 SZ_Clear(&net_message);
2886 // save space for the header, filled in later
2887 MSG_WriteLong(&net_message, 0);
2888 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2889 MSG_WriteString(&net_message, "QUAKE");
2890 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2891 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2892 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2893 SZ_Clear(&net_message);
2895 // search LAN for DarkPlaces servers
2896 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2899 // build the getservers message to send to the dpmaster master servers
2900 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
2902 cmdname = "getserversExt";
2903 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
2907 cmdname = "getservers";
2910 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
2913 for (masternum = 0;sv_masters[masternum].name;masternum++)
2915 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2918 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2922 // search favorite servers
2923 for(j = 0; j < nFavorites; ++j)
2925 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2927 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2928 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
2935 // only query QuakeWorld servers when the user wants to
2938 for (i = 0;i < cl_numsockets;i++)
2942 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2944 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2946 // search LAN for QuakeWorld servers
2947 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2949 // build the getservers message to send to the qwmaster master servers
2950 // note this has no -1 prefix, and the trailing nul byte is sent
2951 dpsnprintf(request, sizeof(request), "c\n");
2955 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2957 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2959 if (m_state != m_slist)
2961 char lookupstring[128];
2962 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2963 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2966 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2970 // search favorite servers
2971 for(j = 0; j < nFavorites; ++j)
2973 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2975 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2977 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
2978 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
2985 if (!masterquerycount)
2987 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2988 M_Update_Return_Reason("No network");
2992 void NetConn_Heartbeat(int priority)
2994 lhnetaddress_t masteraddress;
2996 lhnetsocket_t *mysocket;
2998 // if it's a state change (client connected), limit next heartbeat to no
2999 // more than 30 sec in the future
3000 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3001 nextheartbeattime = realtime + 30.0;
3003 // limit heartbeatperiod to 30 to 270 second range,
3004 // lower limit is to avoid abusing master servers with excess traffic,
3005 // upper limit is to avoid timing out on the master server (which uses
3007 if (sv_heartbeatperiod.value < 30)
3008 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3009 if (sv_heartbeatperiod.value > 270)
3010 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3012 // make advertising optional and don't advertise singleplayer games, and
3013 // only send a heartbeat as often as the admin wants
3014 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3016 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3017 for (masternum = 0;sv_masters[masternum].name;masternum++)
3018 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3019 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3023 static void Net_Heartbeat_f(void)
3026 NetConn_Heartbeat(2);
3028 Con_Print("No server running, can not heartbeat to master server.\n");
3031 void PrintStats(netconn_t *conn)
3033 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3034 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3036 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3039 void Net_Stats_f(void)
3042 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3043 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3044 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3045 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3046 Con_Printf("packetsSent = %i\n", packetsSent);
3047 Con_Printf("packetsReSent = %i\n", packetsReSent);
3048 Con_Printf("packetsReceived = %i\n", packetsReceived);
3049 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3050 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3051 Con_Print("connections =\n");
3052 for (conn = netconn_list;conn;conn = conn->next)
3056 void Net_Refresh_f(void)
3058 if (m_state != m_slist) {
3059 Con_Print("Sending new requests to master servers\n");
3060 ServerList_QueryList(false, true, false, true);
3061 Con_Print("Listening for replies...\n");
3063 ServerList_QueryList(false, true, false, false);
3066 void Net_Slist_f(void)
3068 ServerList_ResetMasks();
3069 serverlist_sortbyfield = SLIF_PING;
3070 serverlist_sortflags = 0;
3071 if (m_state != m_slist) {
3072 Con_Print("Sending requests to master servers\n");
3073 ServerList_QueryList(true, true, false, true);
3074 Con_Print("Listening for replies...\n");
3076 ServerList_QueryList(true, true, false, false);
3079 void Net_SlistQW_f(void)
3081 ServerList_ResetMasks();
3082 serverlist_sortbyfield = SLIF_PING;
3083 serverlist_sortflags = 0;
3084 if (m_state != m_slist) {
3085 Con_Print("Sending requests to master servers\n");
3086 ServerList_QueryList(true, false, true, true);
3087 serverlist_consoleoutput = true;
3088 Con_Print("Listening for replies...\n");
3090 ServerList_QueryList(true, false, true, false);
3093 void NetConn_Init(void)
3096 lhnetaddress_t tempaddress;
3097 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3098 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3099 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3100 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3101 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3102 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3103 Cvar_RegisterVariable(&rcon_restricted_password);
3104 Cvar_RegisterVariable(&rcon_restricted_commands);
3105 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3106 Cvar_RegisterVariable(&net_slist_queriespersecond);
3107 Cvar_RegisterVariable(&net_slist_queriesperframe);
3108 Cvar_RegisterVariable(&net_slist_timeout);
3109 Cvar_RegisterVariable(&net_slist_maxtries);
3110 Cvar_RegisterVariable(&net_slist_favorites);
3111 Cvar_RegisterVariable(&net_slist_pause);
3112 Cvar_RegisterVariable(&net_messagetimeout);
3113 Cvar_RegisterVariable(&net_connecttimeout);
3114 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3115 Cvar_RegisterVariable(&cl_netlocalping);
3116 Cvar_RegisterVariable(&cl_netpacketloss_send);
3117 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3118 Cvar_RegisterVariable(&hostname);
3119 Cvar_RegisterVariable(&developer_networking);
3120 Cvar_RegisterVariable(&cl_netport);
3121 Cvar_RegisterVariable(&sv_netport);
3122 Cvar_RegisterVariable(&net_address);
3123 Cvar_RegisterVariable(&net_address_ipv6);
3124 Cvar_RegisterVariable(&sv_public);
3125 Cvar_RegisterVariable(&sv_heartbeatperiod);
3126 for (i = 0;sv_masters[i].name;i++)
3127 Cvar_RegisterVariable(&sv_masters[i]);
3128 Cvar_RegisterVariable(&gameversion);
3129 // 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.
3130 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3132 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3134 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3135 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3138 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3140 // 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
3141 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3143 i = atoi(com_argv[i + 1]);
3144 if (i >= 0 && i < 65536)
3146 Con_Printf("-port option used, setting port cvar to %i\n", i);
3147 Cvar_SetValueQuick(&sv_netport, i);
3150 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3154 net_message.data = net_message_buf;
3155 net_message.maxsize = sizeof(net_message_buf);
3156 net_message.cursize = 0;
3160 void NetConn_Shutdown(void)
3162 NetConn_CloseClientPorts();
3163 NetConn_CloseServerPorts();