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 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
878 lhnetaddress_t address;
881 char addressstring2[1024];
883 for (port = defaultport; port <= defaultport + 100; port++)
885 if (LHNETADDRESS_FromString(&address, addressstring, port))
887 if ((s = LHNET_OpenSocket_Connectionless(&address)))
889 sv_sockets[sv_numsockets++] = s;
890 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
891 Con_Printf("Server listening on address %s\n", addressstring2);
896 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
897 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
902 Con_Printf("Server unable to parse address %s\n", addressstring);
903 // if it cant parse one address, it wont be able to parse another for sure
909 void NetConn_OpenServerPorts(int opennetports)
912 NetConn_CloseServerPorts();
913 NetConn_UpdateSockets();
914 port = bound(0, sv_netport.integer, 65535);
917 Con_Printf("Server using port %i\n", port);
918 if (sv_netport.integer != port)
919 Cvar_SetValueQuick(&sv_netport, port);
920 if (cls.state != ca_dedicated)
921 NetConn_OpenServerPort("local:1", 0);
924 NetConn_OpenServerPort(net_address.string, port);
925 NetConn_OpenServerPort(net_address_ipv6.string, port);
927 if (sv_numsockets == 0)
928 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
931 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
933 int i, a = LHNETADDRESS_GetAddressType(address);
934 for (i = 0;i < cl_numsockets;i++)
935 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
936 return cl_sockets[i];
940 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
942 int i, a = LHNETADDRESS_GetAddressType(address);
943 for (i = 0;i < sv_numsockets;i++)
944 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
945 return sv_sockets[i];
949 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
952 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
953 conn->mysocket = mysocket;
954 conn->peeraddress = *peeraddress;
955 conn->lastMessageTime = realtime;
956 conn->message.data = conn->messagedata;
957 conn->message.maxsize = sizeof(conn->messagedata);
958 conn->message.cursize = 0;
959 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
960 // reduce effectiveness of connection request floods
961 conn->timeout = realtime + net_connecttimeout.value;
962 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
963 conn->next = netconn_list;
968 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
969 void NetConn_Close(netconn_t *conn)
972 // remove connection from list
974 // allow the client to reconnect immediately
975 NetConn_ClearConnectFlood(&(conn->peeraddress));
977 if (conn == netconn_list)
978 netconn_list = conn->next;
981 for (c = netconn_list;c;c = c->next)
985 c->next = conn->next;
989 // not found in list, we'll avoid crashing here...
997 static int clientport = -1;
998 static int clientport2 = -1;
999 static int hostport = -1;
1000 void NetConn_UpdateSockets(void)
1002 if (cls.state != ca_dedicated)
1004 if (clientport2 != cl_netport.integer)
1006 clientport2 = cl_netport.integer;
1007 if (cls.state == ca_connected)
1008 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1010 if (cls.state == ca_disconnected && clientport != clientport2)
1012 clientport = clientport2;
1013 NetConn_CloseClientPorts();
1015 if (cl_numsockets == 0)
1016 NetConn_OpenClientPorts();
1019 if (hostport != sv_netport.integer)
1021 hostport = sv_netport.integer;
1023 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1027 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1029 int originallength = length;
1033 if (protocol == PROTOCOL_QUAKEWORLD)
1035 int sequence, sequence_ack;
1036 int reliable_ack, reliable_message;
1040 sequence = LittleLong(*((int *)(data + 0)));
1041 sequence_ack = LittleLong(*((int *)(data + 4)));
1045 if (conn != cls.netcon)
1050 // TODO: use qport to identify that this client really is who they say they are? (and elsewhere in the code to identify the connection without a port match?)
1051 qport = LittleShort(*((int *)(data + 8)));
1057 reliable_message = (sequence >> 31) & 1;
1058 reliable_ack = (sequence_ack >> 31) & 1;
1059 sequence &= ~(1<<31);
1060 sequence_ack &= ~(1<<31);
1061 if (sequence <= conn->qw.incoming_sequence)
1063 //Con_DPrint("Got a stale datagram\n");
1066 count = sequence - (conn->qw.incoming_sequence + 1);
1069 droppedDatagrams += count;
1070 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1073 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1074 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1075 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1076 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1079 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1080 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1081 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1082 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1083 if (reliable_ack == conn->qw.reliable_sequence)
1085 // received, now we will be able to send another reliable message
1086 conn->sendMessageLength = 0;
1087 reliableMessagesReceived++;
1089 conn->qw.incoming_sequence = sequence;
1090 if (conn == cls.netcon)
1091 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1092 conn->qw.incoming_acknowledged = sequence_ack;
1093 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1094 if (reliable_message)
1095 conn->qw.incoming_reliable_sequence ^= 1;
1096 conn->lastMessageTime = realtime;
1097 conn->timeout = realtime + newtimeout;
1098 unreliableMessagesReceived++;
1099 SZ_Clear(&net_message);
1100 SZ_Write(&net_message, data, length);
1108 unsigned int sequence;
1111 qlength = (unsigned int)BigLong(((int *)data)[0]);
1112 flags = qlength & ~NETFLAG_LENGTH_MASK;
1113 qlength &= NETFLAG_LENGTH_MASK;
1114 // control packets were already handled
1115 if (!(flags & NETFLAG_CTL) && qlength == length)
1117 sequence = BigLong(((int *)data)[1]);
1121 if (flags & NETFLAG_UNRELIABLE)
1123 if (sequence >= conn->nq.unreliableReceiveSequence)
1125 if (sequence > conn->nq.unreliableReceiveSequence)
1127 count = sequence - conn->nq.unreliableReceiveSequence;
1128 droppedDatagrams += count;
1129 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1132 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1133 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1134 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1135 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1138 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1139 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1140 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1141 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1142 conn->nq.unreliableReceiveSequence = sequence + 1;
1143 conn->lastMessageTime = realtime;
1144 conn->timeout = realtime + newtimeout;
1145 unreliableMessagesReceived++;
1148 SZ_Clear(&net_message);
1149 SZ_Write(&net_message, data, length);
1155 // Con_DPrint("Got a stale datagram\n");
1158 else if (flags & NETFLAG_ACK)
1160 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1161 if (sequence == (conn->nq.sendSequence - 1))
1163 if (sequence == conn->nq.ackSequence)
1165 conn->nq.ackSequence++;
1166 if (conn->nq.ackSequence != conn->nq.sendSequence)
1167 Con_DPrint("ack sequencing error\n");
1168 conn->lastMessageTime = realtime;
1169 conn->timeout = realtime + newtimeout;
1170 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1172 unsigned int packetLen;
1173 unsigned int dataLen;
1175 unsigned int *header;
1177 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1178 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1180 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1182 dataLen = conn->sendMessageLength;
1187 dataLen = MAX_PACKETFRAGMENT;
1191 packetLen = NET_HEADERSIZE + dataLen;
1193 header = (unsigned int *)sendbuffer;
1194 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1195 header[1] = BigLong(conn->nq.sendSequence);
1196 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1198 conn->nq.sendSequence++;
1200 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1202 conn->lastSendTime = realtime;
1207 conn->sendMessageLength = 0;
1210 // Con_DPrint("Duplicate ACK received\n");
1213 // Con_DPrint("Stale ACK received\n");
1216 else if (flags & NETFLAG_DATA)
1218 unsigned int temppacket[2];
1219 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1220 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1221 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1222 temppacket[1] = BigLong(sequence);
1223 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1224 if (sequence == conn->nq.receiveSequence)
1226 conn->lastMessageTime = realtime;
1227 conn->timeout = realtime + newtimeout;
1228 conn->nq.receiveSequence++;
1229 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1230 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1231 conn->receiveMessageLength += length;
1233 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1234 "Dropping the message!\n", sequence );
1235 conn->receiveMessageLength = 0;
1238 if (flags & NETFLAG_EOM)
1240 reliableMessagesReceived++;
1241 length = conn->receiveMessageLength;
1242 conn->receiveMessageLength = 0;
1245 SZ_Clear(&net_message);
1246 SZ_Write(&net_message, conn->receiveMessage, length);
1253 receivedDuplicateCount++;
1261 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1263 cls.connect_trying = false;
1264 M_Update_Return_Reason("");
1265 // the connection request succeeded, stop current connection and set up a new connection
1267 // if we're connecting to a remote server, shut down any local server
1268 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1269 Host_ShutdownServer ();
1270 // allocate a net connection to keep track of things
1271 cls.netcon = NetConn_Open(mysocket, peeraddress);
1272 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1273 key_dest = key_game;
1275 cls.demonum = -1; // not in the demo loop now
1276 cls.state = ca_connected;
1277 cls.signon = 0; // need all the signon messages before playing
1278 cls.protocol = initialprotocol;
1279 // reset move sequence numbering on this new connection
1280 cls.servermovesequence = 0;
1281 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1282 Cmd_ForwardStringToServer("new");
1283 if (cls.protocol == PROTOCOL_QUAKE)
1285 // write a keepalive (clc_nop) as it seems to greatly improve the
1286 // chances of connecting to a netquake server
1288 unsigned char buf[4];
1289 memset(&msg, 0, sizeof(msg));
1291 msg.maxsize = sizeof(buf);
1292 MSG_WriteChar(&msg, clc_nop);
1293 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1297 int NetConn_IsLocalGame(void)
1299 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1304 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1308 serverlist_entry_t *entry = NULL;
1310 // search the cache for this server and update it
1311 for (n = 0;n < serverlist_cachecount;n++) {
1312 entry = &serverlist_cache[ n ];
1313 if (!strcmp(addressstring, entry->info.cname))
1317 if (n == serverlist_cachecount)
1319 // LAN search doesnt require an answer from the master server so we wont
1320 // know the ping nor will it be initialized already...
1323 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1326 entry = &serverlist_cache[n];
1328 memset(entry, 0, sizeof(*entry));
1329 // store the data the engine cares about (address and ping)
1330 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1331 entry->info.ping = 100000;
1332 entry->querytime = realtime;
1333 // if not in the slist menu we should print the server to console
1334 if (serverlist_consoleoutput)
1335 Con_Printf("querying %s\n", addressstring);
1336 ++serverlist_cachecount;
1338 // if this is the first reply from this server, count it as having replied
1339 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1340 pingtime = bound(0, pingtime, 9999);
1341 if (entry->query == SQS_REFRESHING) {
1342 entry->info.ping = pingtime;
1343 entry->query = SQS_QUERIED;
1345 // convert to unsigned to catch the -1
1346 // I still dont like this but its better than the old 10000 magic ping number - as in easier to type and read :( [11/8/2007 Black]
1347 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1351 // other server info is updated by the caller
1355 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1357 serverlist_entry_t *entry = &serverlist_cache[n];
1358 serverlist_info_t *info = &entry->info;
1359 // update description strings for engine menu and console output
1360 dpsnprintf(entry->line1, sizeof(serverlist_cache[n].line1), "^%c%5d^7 ^%c%3u^7/%3u %-65.65s", info->ping >= 300 ? '1' : (info->ping >= 200 ? '3' : '7'), (int)info->ping, ((info->numhumans > 0 && info->numhumans < info->maxplayers) ? (info->numhumans >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1361 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
1362 if (entry->query == SQS_QUERIED)
1364 if(!serverlist_paused)
1365 ServerList_ViewList_Remove(entry);
1367 // if not in the slist menu we should print the server to console (if wanted)
1368 else if( serverlist_consoleoutput )
1369 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1370 // and finally, update the view set
1371 if(!serverlist_paused)
1372 ServerList_ViewList_Insert( entry );
1373 // update the entry's state
1374 serverlist_cache[n].query = SQS_QUERIED;
1377 // returns true, if it's sensible to continue the processing
1378 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1380 serverlist_entry_t *entry;
1382 // ignore the rest of the message if the serverlist is full
1383 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1385 // also ignore it if we have already queried it (other master server response)
1386 for( n = 0 ; n < serverlist_cachecount ; n++ )
1387 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1390 entry = &serverlist_cache[n];
1392 if( n < serverlist_cachecount ) {
1393 // the entry has already been queried once or
1397 memset(entry, 0, sizeof(entry));
1398 entry->protocol = protocol;
1399 // store the data the engine cares about (address and ping)
1400 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1402 entry->info.isfavorite = isfavorite;
1404 // no, then reset the ping right away
1405 entry->info.ping = -1;
1406 // we also want to increase the serverlist_cachecount then
1407 serverlist_cachecount++;
1410 entry->query = SQS_QUERYING;
1415 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1418 if (serverlist_consoleoutput)
1419 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1422 char ipstring [128];
1425 if (data[0] == '\\')
1427 unsigned short port = data[5] * 256 + data[6];
1429 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1430 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1432 // move on to next address in packet
1437 else if (data[0] == '/' && isextended && length >= 19)
1439 unsigned short port = data[17] * 256 + data[18];
1445 // TODO: make some basic checks of the IP address (broadcast, ...)
1447 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1450 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1451 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1452 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1457 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1458 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1459 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1464 // move on to next address in packet
1470 Con_Print("Error while parsing the server list\n");
1474 if (serverlist_consoleoutput && developer_networking.integer)
1475 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1477 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1483 // begin or resume serverlist queries
1484 serverlist_querysleep = false;
1485 serverlist_querywaittime = realtime + 3;
1488 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1490 qboolean fromserver;
1491 int ret, c, control;
1493 char *string, addressstring2[128], ipstring[32];
1494 char stringbuf[16384];
1496 // quakeworld ingame packet
1497 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1499 // convert the address to a string incase we need it
1500 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1502 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1504 // received a command string - strip off the packaging and put it
1505 // into our string buffer with NULL termination
1508 length = min(length, (int)sizeof(stringbuf) - 1);
1509 memcpy(stringbuf, data, length);
1510 stringbuf[length] = 0;
1513 if (developer_networking.integer)
1515 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1516 Com_HexDumpToConsole(data, length);
1519 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1521 // darkplaces or quake3
1522 char protocolnames[1400];
1523 Protocol_Names(protocolnames, sizeof(protocolnames));
1524 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1525 M_Update_Return_Reason("Got challenge response");
1526 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1527 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1528 // TODO: add userinfo stuff here instead of using NQ commands?
1529 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1532 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1534 // darkplaces or quake3
1535 M_Update_Return_Reason("Accepted");
1536 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1539 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1541 char rejectreason[32];
1542 cls.connect_trying = false;
1544 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1545 memcpy(rejectreason, string, length);
1546 rejectreason[length] = 0;
1547 M_Update_Return_Reason(rejectreason);
1550 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1552 serverlist_info_t *info;
1557 // search the cache for this server and update it
1558 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1562 info = &serverlist_cache[n].info;
1567 info->qcstatus[0] = 0;
1568 info->players[0] = 0;
1569 info->protocol = -1;
1570 info->numplayers = 0;
1572 info->maxplayers = 0;
1573 info->gameversion = 0;
1575 p = strchr(string, '\n');
1578 *p = 0; // cut off the string there
1582 Con_Printf("statusResponse without players block?\n");
1584 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1585 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1586 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1587 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1588 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1589 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1590 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1591 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1592 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1593 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1594 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1595 info->numhumans = info->numplayers - max(0, info->numbots);
1596 info->freeslots = info->maxplayers - info->numplayers;
1598 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1602 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1604 serverlist_info_t *info;
1608 // search the cache for this server and update it
1609 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1613 info = &serverlist_cache[n].info;
1618 info->qcstatus[0] = 0;
1619 info->players[0] = 0;
1620 info->protocol = -1;
1621 info->numplayers = 0;
1623 info->maxplayers = 0;
1624 info->gameversion = 0;
1626 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1627 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1628 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1629 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1630 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1631 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1632 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1633 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1634 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1635 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1636 info->numhumans = info->numplayers - max(0, info->numbots);
1637 info->freeslots = info->maxplayers - info->numplayers;
1639 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1643 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1645 // Extract the IP addresses
1648 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1651 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1653 // Extract the IP addresses
1656 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1659 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1661 // Extract the IP addresses
1665 if (serverlist_consoleoutput)
1666 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1667 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1669 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1670 if (serverlist_consoleoutput && developer_networking.integer)
1671 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1673 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1677 // move on to next address in packet
1681 // begin or resume serverlist queries
1682 serverlist_querysleep = false;
1683 serverlist_querywaittime = realtime + 3;
1686 if (!strncmp(string, "extResponse ", 12))
1688 ++net_extresponse_count;
1689 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1690 net_extresponse_count = NET_EXTRESPONSE_MAX;
1691 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1692 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1695 if (!strncmp(string, "ping", 4))
1697 if (developer.integer >= 10)
1698 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1699 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1702 if (!strncmp(string, "ack", 3))
1704 // QuakeWorld compatibility
1705 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1707 // challenge message
1708 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1709 M_Update_Return_Reason("Got QuakeWorld challenge response");
1710 cls.qw_qport = qport.integer;
1711 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1712 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1713 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1716 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1719 M_Update_Return_Reason("QuakeWorld Accepted");
1720 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1723 if (length > 2 && !memcmp(string, "n\\", 2))
1725 serverlist_info_t *info;
1729 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1730 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1733 // search the cache for this server and update it
1734 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1738 info = &serverlist_cache[n].info;
1739 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1740 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1741 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1742 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1744 info->numplayers = 0; // updated below
1745 info->numhumans = 0; // updated below
1746 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1747 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1749 // count active players on server
1750 // (we could gather more info, but we're just after the number)
1751 s = strchr(string, '\n');
1755 while (s < string + length)
1757 for (;s < string + length && *s != '\n';s++)
1759 if (s >= string + length)
1767 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1771 if (string[0] == 'n')
1774 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1776 // we may not have liked the packet, but it was a command packet, so
1777 // we're done processing this packet now
1780 // quakeworld ingame packet
1781 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1784 CL_ParseServerMessage();
1787 // netquake control packets, supported for compatibility only
1788 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1791 serverlist_info_t *info;
1795 SZ_Clear(&net_message);
1796 SZ_Write(&net_message, data, length);
1802 if (developer.integer >= 10)
1803 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1804 if (cls.connect_trying)
1806 lhnetaddress_t clientportaddress;
1807 clientportaddress = *peeraddress;
1808 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1809 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1810 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1811 M_Update_Return_Reason("Accepted");
1812 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1816 if (developer.integer >= 10)
1817 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1818 cls.connect_trying = false;
1819 M_Update_Return_Reason((char *)MSG_ReadString());
1821 case CCREP_SERVER_INFO:
1822 if (developer.integer >= 10)
1823 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1824 // LordHavoc: because the quake server may report weird addresses
1825 // we just ignore it and keep the real address
1827 // search the cache for this server and update it
1828 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1832 info = &serverlist_cache[n].info;
1833 strlcpy(info->game, "Quake", sizeof(info->game));
1834 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1835 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1836 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1837 info->numplayers = MSG_ReadByte();
1838 info->maxplayers = MSG_ReadByte();
1839 info->protocol = MSG_ReadByte();
1841 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1844 case CCREP_PLAYER_INFO:
1845 // we got a CCREP_PLAYER_INFO??
1846 //if (developer.integer >= 10)
1847 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1849 case CCREP_RULE_INFO:
1850 // we got a CCREP_RULE_INFO??
1851 //if (developer.integer >= 10)
1852 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1857 SZ_Clear(&net_message);
1858 // we may not have liked the packet, but it was a valid control
1859 // packet, so we're done processing this packet now
1863 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1864 CL_ParseServerMessage();
1868 void NetConn_QueryQueueFrame(void)
1874 static double querycounter = 0;
1876 if(!net_slist_pause.integer && serverlist_paused)
1877 ServerList_RebuildViewList();
1878 serverlist_paused = net_slist_pause.integer;
1880 if (serverlist_querysleep)
1883 // apply a cool down time after master server replies,
1884 // to avoid messing up the ping times on the servers
1885 if (serverlist_querywaittime > realtime)
1888 // each time querycounter reaches 1.0 issue a query
1889 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1890 maxqueries = (int)querycounter;
1891 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1892 querycounter -= maxqueries;
1894 if( maxqueries == 0 ) {
1898 // scan serverlist and issue queries as needed
1899 serverlist_querysleep = true;
1901 timeouttime = realtime - net_slist_timeout.value;
1902 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1904 serverlist_entry_t *entry = &serverlist_cache[ index ];
1905 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1910 serverlist_querysleep = false;
1911 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1916 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1918 lhnetaddress_t address;
1921 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1922 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1924 for (socket = 0; socket < cl_numsockets ; socket++)
1925 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1929 for (socket = 0; socket < cl_numsockets ; socket++)
1930 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
1933 // update the entry fields
1934 entry->querytime = realtime;
1935 entry->querycounter++;
1937 // if not in the slist menu we should print the server to console
1938 if (serverlist_consoleoutput)
1939 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1945 // have we tried to refresh this server?
1946 if( entry->query == SQS_REFRESHING ) {
1947 // yes, so update the reply count (since its not responding anymore)
1949 if(!serverlist_paused)
1950 ServerList_ViewList_Remove(entry);
1952 entry->query = SQS_TIMEDOUT;
1957 void NetConn_ClientFrame(void)
1960 lhnetaddress_t peeraddress;
1961 NetConn_UpdateSockets();
1962 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1964 if (cls.connect_remainingtries == 0)
1965 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1966 cls.connect_nextsendtime = realtime + 1;
1967 cls.connect_remainingtries--;
1968 if (cls.connect_remainingtries <= -10)
1970 cls.connect_trying = false;
1971 M_Update_Return_Reason("Connect: Failed");
1974 // try challenge first (newer DP server or QW)
1975 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1976 // then try netquake as a fallback (old server, or netquake)
1977 SZ_Clear(&net_message);
1978 // save space for the header, filled in later
1979 MSG_WriteLong(&net_message, 0);
1980 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1981 MSG_WriteString(&net_message, "QUAKE");
1982 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1983 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1984 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1985 SZ_Clear(&net_message);
1987 for (i = 0;i < cl_numsockets;i++)
1988 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1989 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1990 NetConn_QueryQueueFrame();
1991 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1993 Con_Print("Connection timed out\n");
1995 Host_ShutdownServer ();
1999 #define MAX_CHALLENGES 128
2002 lhnetaddress_t address;
2006 challenge[MAX_CHALLENGES];
2008 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2012 for (i = 0;i < bufferlength - 1;i++)
2016 c = rand () % (127 - 33) + 33;
2017 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2023 // (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2024 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2027 unsigned int nb_clients = 0, nb_bots = 0, i;
2033 // How many clients are there?
2034 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2036 if (svs.clients[i].active)
2039 if (!svs.clients[i].netconnection)
2045 if(prog->globaloffsets.worldstatus >= 0)
2047 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2053 for(q = str; *q; ++q)
2054 if(*q != '\\' && *q != '\n')
2060 // TODO: we should add more information for the full status string
2061 length = dpsnprintf(out_msg, out_size,
2062 "\377\377\377\377%s\x0A"
2063 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2064 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2068 fullstatus ? "statusResponse" : "infoResponse",
2069 gamename, com_modname, gameversion.integer, svs.maxclients,
2070 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2071 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2072 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2073 fullstatus ? "\n" : "");
2075 // Make sure it fits in the buffer
2085 savelength = length;
2087 ptr = out_msg + length;
2088 left = (int)out_size - length;
2090 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2092 client_t *cl = &svs.clients[i];
2095 int nameind, cleanind, pingvalue;
2097 char cleanname [sizeof(cl->name)];
2099 // Remove all characters '"' and '\' in the player name
2104 curchar = cl->name[nameind++];
2105 if (curchar != '"' && curchar != '\\')
2107 cleanname[cleanind++] = curchar;
2108 if (cleanind == sizeof(cleanname) - 1)
2111 } while (curchar != '\0');
2112 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2114 pingvalue = (int)(cl->ping * 1000.0f);
2115 if(cl->netconnection)
2116 pingvalue = bound(1, pingvalue, 9999);
2121 if(prog->fieldoffsets.clientstatus >= 0)
2123 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2129 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2130 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2136 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2138 if(cl->frags == -666) // spectator
2139 strlcpy(teambuf, " 0", sizeof(teambuf));
2140 else if(cl->colors == 0x44) // red team
2141 strlcpy(teambuf, " 1", sizeof(teambuf));
2142 else if(cl->colors == 0xDD) // blue team
2143 strlcpy(teambuf, " 2", sizeof(teambuf));
2144 else if(cl->colors == 0xCC) // yellow team
2145 strlcpy(teambuf, " 3", sizeof(teambuf));
2146 else if(cl->colors == 0x99) // pink team
2147 strlcpy(teambuf, " 4", sizeof(teambuf));
2149 strlcpy(teambuf, " 0", sizeof(teambuf));
2154 // note: team number is inserted according to SoF2 protocol
2156 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2162 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2171 // turn it into an infoResponse!
2172 out_msg[savelength] = 0;
2173 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2174 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2191 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2193 int floodslotnum, bestfloodslotnum;
2194 double bestfloodtime;
2195 lhnetaddress_t noportpeeraddress;
2196 // see if this is a connect flood
2197 noportpeeraddress = *peeraddress;
2198 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2199 bestfloodslotnum = 0;
2200 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2201 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2203 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2205 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2206 bestfloodslotnum = floodslotnum;
2208 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2210 // this address matches an ongoing flood address
2211 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2213 // renew the ban on this address so it does not expire
2214 // until the flood has subsided
2215 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2216 //Con_Printf("Flood detected!\n");
2219 // the flood appears to have subsided, so allow this
2220 bestfloodslotnum = floodslotnum; // reuse the same slot
2224 // begin a new timeout on this address
2225 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2226 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2227 //Con_Printf("Flood detection initiated!\n");
2231 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2234 lhnetaddress_t noportpeeraddress;
2235 // see if this is a connect flood
2236 noportpeeraddress = *peeraddress;
2237 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2238 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2240 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2242 // this address matches an ongoing flood address
2244 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2245 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2246 //Con_Printf("Flood cleared!\n");
2251 typedef qboolean (*rcon_matchfunc_t) (const char *password, const char *hash, const char *s, int slen);
2253 qboolean hmac_mdfour_matching(const char *password, const char *hash, const char *s, int slen)
2258 t1 = (long) time(NULL);
2259 t2 = strtol(s, NULL, 0);
2260 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2263 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2266 return !memcmp(mdfourbuf, hash, 16);
2269 qboolean plaintext_matching(const char *password, const char *hash, const char *s, int slen)
2271 return !strcmp(password, hash);
2274 // returns a string describing the user level, or NULL for auth failure
2275 const char *RCon_Authenticate(const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2280 if(comparator(rcon_password.string, password, cs, cslen))
2283 if(!comparator(rcon_restricted_password.string, password, cs, cslen))
2286 for(text = s; text != endpos; ++text)
2287 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2288 return NULL; // block possible exploits against the parser/alias expansion
2292 size_t l = strlen(s);
2295 hasquotes = (strchr(s, '"') != NULL);
2296 // sorry, we can't allow these substrings in wildcard expressions,
2297 // as they can mess with the argument counts
2298 text = rcon_restricted_commands.string;
2299 while(COM_ParseToken_Console(&text))
2301 // com_token now contains a pattern to check for...
2302 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2305 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2308 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2310 if(!strcmp(com_token, s))
2313 else // single-arg expression? must match the beginning of the command
2315 if(!strcmp(com_token, s))
2317 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2321 // if we got here, nothing matched!
2328 return "restricted rcon";
2331 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2335 // looks like a legitimate rcon command with the correct password
2336 const char *s_ptr = s;
2337 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2338 while(s_ptr != endpos)
2340 size_t l = strlen(s_ptr);
2342 Con_Printf(" %s;", s_ptr);
2347 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2348 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2351 size_t l = strlen(s);
2354 client_t *host_client_save = host_client;
2355 Cmd_ExecuteString(s, src_command);
2356 host_client = host_client_save;
2357 // in case it is a command that changes host_client (like restart)
2361 Con_Rcon_Redirect_End();
2365 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2369 extern void SV_SendServerinfo (client_t *client);
2370 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2372 int i, ret, clientnum, best;
2375 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2376 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2381 // convert the address to a string incase we need it
2382 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2384 // see if we can identify the sender as a local player
2385 // (this is necessary for rcon to send a reliable reply if the client is
2386 // actually on the server, not sending remotely)
2387 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2388 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2390 if (i == svs.maxclients)
2393 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2395 // received a command string - strip off the packaging and put it
2396 // into our string buffer with NULL termination
2399 length = min(length, (int)sizeof(stringbuf) - 1);
2400 memcpy(stringbuf, data, length);
2401 stringbuf[length] = 0;
2404 if (developer.integer >= 10)
2406 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2407 Com_HexDumpToConsole(data, length);
2410 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2412 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2414 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2416 if (besttime > challenge[i].time)
2417 besttime = challenge[best = i].time;
2419 // if we did not find an exact match, choose the oldest and
2420 // update address and string
2421 if (i == MAX_CHALLENGES)
2424 challenge[i].address = *peeraddress;
2425 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2427 challenge[i].time = realtime;
2428 // send the challenge
2429 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2432 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2437 if (!(s = SearchInfostring(string, "challenge")))
2439 // validate the challenge
2440 for (i = 0;i < MAX_CHALLENGES;i++)
2441 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2443 // if the challenge is not recognized, drop the packet
2444 if (i == MAX_CHALLENGES)
2447 // check engine protocol
2448 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2450 if (developer.integer >= 10)
2451 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2452 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2456 // see if this is a duplicate connection request or a disconnected
2457 // client who is rejoining to the same client slot
2458 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2460 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2462 // this is a known client...
2463 if (client->spawned)
2465 // client crashed and is coming back,
2466 // keep their stuff intact
2467 if (developer.integer >= 10)
2468 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2469 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2471 SV_SendServerinfo(client);
2476 // client is still trying to connect,
2477 // so we send a duplicate reply
2478 if (developer.integer >= 10)
2479 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2480 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2486 if (NetConn_PreventConnectFlood(peeraddress))
2489 // find an empty client slot for this new client
2490 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2493 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2495 // allocated connection
2496 if (developer.integer >= 10)
2497 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2498 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2499 // now set up the client
2501 SV_ConnectClient(clientnum, conn);
2503 NetConn_Heartbeat(1);
2508 // no empty slots found - server is full
2509 if (developer.integer >= 10)
2510 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2511 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2515 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2517 const char *challenge = NULL;
2519 // If there was a challenge in the getinfo message
2520 if (length > 8 && string[7] == ' ')
2521 challenge = string + 8;
2523 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2525 if (developer.integer >= 10)
2526 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2527 NetConn_WriteString(mysocket, response, peeraddress);
2531 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2533 const char *challenge = NULL;
2535 // If there was a challenge in the getinfo message
2536 if (length > 10 && string[9] == ' ')
2537 challenge = string + 10;
2539 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2541 if (developer.integer >= 10)
2542 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2543 NetConn_WriteString(mysocket, response, peeraddress);
2547 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2549 char *password = string + 20;
2550 char *timeval = string + 37;
2551 char *s = strchr(timeval, ' ');
2552 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2553 const char *userlevel;
2555 return true; // invalid packet
2558 userlevel = RCon_Authenticate(password, s, endpos, hmac_mdfour_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2559 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2562 if (length >= 5 && !memcmp(string, "rcon ", 5))
2565 char *s = string + 5;
2566 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2569 if(rcon_secure.integer)
2572 for (i = 0;!ISWHITESPACE(*s);s++)
2573 if (i < (int)sizeof(password) - 1)
2575 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2578 if (!ISWHITESPACE(password[0]))
2580 const char *userlevel = RCon_Authenticate(password, s, endpos, plaintext_matching, NULL, 0);
2581 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2585 if (!strncmp(string, "ping", 4))
2587 if (developer.integer >= 10)
2588 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2589 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2592 if (!strncmp(string, "ack", 3))
2594 // we may not have liked the packet, but it was a command packet, so
2595 // we're done processing this packet now
2598 // netquake control packets, supported for compatibility only, and only
2599 // when running game protocols that are normally served via this connection
2601 // (this protects more modern protocols against being used for
2602 // Quake packet flood Denial Of Service attacks)
2603 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))
2607 const char *protocolname;
2610 SZ_Clear(&net_message);
2611 SZ_Write(&net_message, data, length);
2617 if (developer.integer >= 10)
2618 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2619 if(!islocal && sv_public.integer <= -2)
2622 protocolname = MSG_ReadString();
2623 protocolnumber = MSG_ReadByte();
2624 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2626 if (developer.integer >= 10)
2627 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2628 SZ_Clear(&net_message);
2629 // save space for the header, filled in later
2630 MSG_WriteLong(&net_message, 0);
2631 MSG_WriteByte(&net_message, CCREP_REJECT);
2632 MSG_WriteString(&net_message, "Incompatible version.\n");
2633 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2634 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2635 SZ_Clear(&net_message);
2639 // see if this connect request comes from a known client
2640 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2642 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2644 // this is either a duplicate connection request
2645 // or coming back from a timeout
2646 // (if so, keep their stuff intact)
2649 if (developer.integer >= 10)
2650 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2651 SZ_Clear(&net_message);
2652 // save space for the header, filled in later
2653 MSG_WriteLong(&net_message, 0);
2654 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2655 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2656 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2657 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2658 SZ_Clear(&net_message);
2660 // if client is already spawned, re-send the
2661 // serverinfo message as they'll need it to play
2662 if (client->spawned)
2665 SV_SendServerinfo(client);
2672 // this is a new client, check for connection flood
2673 if (NetConn_PreventConnectFlood(peeraddress))
2676 // find a slot for the new client
2677 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2680 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2682 // connect to the client
2683 // everything is allocated, just fill in the details
2684 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2685 if (developer.integer >= 10)
2686 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2687 // send back the info about the server connection
2688 SZ_Clear(&net_message);
2689 // save space for the header, filled in later
2690 MSG_WriteLong(&net_message, 0);
2691 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2692 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2693 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2694 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2695 SZ_Clear(&net_message);
2696 // now set up the client struct
2698 SV_ConnectClient(clientnum, conn);
2700 NetConn_Heartbeat(1);
2705 if (developer.integer >= 10)
2706 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2707 // no room; try to let player know
2708 SZ_Clear(&net_message);
2709 // save space for the header, filled in later
2710 MSG_WriteLong(&net_message, 0);
2711 MSG_WriteByte(&net_message, CCREP_REJECT);
2712 MSG_WriteString(&net_message, "Server is full.\n");
2713 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2714 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2715 SZ_Clear(&net_message);
2717 case CCREQ_SERVER_INFO:
2718 if (developer.integer >= 10)
2719 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2720 if(!islocal && sv_public.integer <= -1)
2722 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2725 char myaddressstring[128];
2726 if (developer.integer >= 10)
2727 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2728 SZ_Clear(&net_message);
2729 // save space for the header, filled in later
2730 MSG_WriteLong(&net_message, 0);
2731 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2732 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2733 MSG_WriteString(&net_message, myaddressstring);
2734 MSG_WriteString(&net_message, hostname.string);
2735 MSG_WriteString(&net_message, sv.name);
2736 // How many clients are there?
2737 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2738 if (svs.clients[i].active)
2740 MSG_WriteByte(&net_message, numclients);
2741 MSG_WriteByte(&net_message, svs.maxclients);
2742 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2743 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2744 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2745 SZ_Clear(&net_message);
2748 case CCREQ_PLAYER_INFO:
2749 if (developer.integer >= 10)
2750 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2751 if(!islocal && sv_public.integer <= -1)
2755 int playerNumber, activeNumber, clientNumber;
2758 playerNumber = MSG_ReadByte();
2760 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2761 if (client->active && ++activeNumber == playerNumber)
2763 if (clientNumber != svs.maxclients)
2765 SZ_Clear(&net_message);
2766 // save space for the header, filled in later
2767 MSG_WriteLong(&net_message, 0);
2768 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2769 MSG_WriteByte(&net_message, playerNumber);
2770 MSG_WriteString(&net_message, client->name);
2771 MSG_WriteLong(&net_message, client->colors);
2772 MSG_WriteLong(&net_message, client->frags);
2773 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2774 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2775 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2776 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2777 SZ_Clear(&net_message);
2781 case CCREQ_RULE_INFO:
2782 if (developer.integer >= 10)
2783 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2784 if(!islocal && sv_public.integer <= -1)
2791 // find the search start location
2792 prevCvarName = MSG_ReadString();
2793 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2795 // send the response
2796 SZ_Clear(&net_message);
2797 // save space for the header, filled in later
2798 MSG_WriteLong(&net_message, 0);
2799 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2802 MSG_WriteString(&net_message, var->name);
2803 MSG_WriteString(&net_message, var->string);
2805 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2806 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2807 SZ_Clear(&net_message);
2813 SZ_Clear(&net_message);
2814 // we may not have liked the packet, but it was a valid control
2815 // packet, so we're done processing this packet now
2820 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2823 SV_ReadClientMessage();
2831 void NetConn_ServerFrame(void)
2834 lhnetaddress_t peeraddress;
2835 for (i = 0;i < sv_numsockets;i++)
2836 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2837 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2838 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2840 // never timeout loopback connections
2841 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2843 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2845 SV_DropClient(false);
2851 void NetConn_SleepMicroseconds(int microseconds)
2853 LHNET_SleepUntilPacket_Microseconds(microseconds);
2856 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2860 lhnetaddress_t masteraddress;
2861 lhnetaddress_t broadcastaddress;
2864 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2867 // 26000 is the default quake server port, servers on other ports will not
2869 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2870 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2874 for (i = 0;i < cl_numsockets;i++)
2878 const char *cmdname, *extraoptions;
2879 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2881 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2883 // search LAN for Quake servers
2884 SZ_Clear(&net_message);
2885 // save space for the header, filled in later
2886 MSG_WriteLong(&net_message, 0);
2887 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2888 MSG_WriteString(&net_message, "QUAKE");
2889 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2890 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2891 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2892 SZ_Clear(&net_message);
2894 // search LAN for DarkPlaces servers
2895 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
2898 // build the getservers message to send to the dpmaster master servers
2899 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
2901 cmdname = "getserversExt";
2902 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
2906 cmdname = "getservers";
2909 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
2912 for (masternum = 0;sv_masters[masternum].name;masternum++)
2914 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
2917 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2921 // search favorite servers
2922 for(j = 0; j < nFavorites; ++j)
2924 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2926 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2927 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
2934 // only query QuakeWorld servers when the user wants to
2937 for (i = 0;i < cl_numsockets;i++)
2941 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
2943 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
2945 // search LAN for QuakeWorld servers
2946 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2948 // build the getservers message to send to the qwmaster master servers
2949 // note this has no -1 prefix, and the trailing nul byte is sent
2950 dpsnprintf(request, sizeof(request), "c\n");
2954 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2956 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2958 if (m_state != m_slist)
2960 char lookupstring[128];
2961 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2962 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2965 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2969 // search favorite servers
2970 for(j = 0; j < nFavorites; ++j)
2972 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
2974 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
2976 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
2977 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
2984 if (!masterquerycount)
2986 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2987 M_Update_Return_Reason("No network");
2991 void NetConn_Heartbeat(int priority)
2993 lhnetaddress_t masteraddress;
2995 lhnetsocket_t *mysocket;
2997 // if it's a state change (client connected), limit next heartbeat to no
2998 // more than 30 sec in the future
2999 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3000 nextheartbeattime = realtime + 30.0;
3002 // limit heartbeatperiod to 30 to 270 second range,
3003 // lower limit is to avoid abusing master servers with excess traffic,
3004 // upper limit is to avoid timing out on the master server (which uses
3006 if (sv_heartbeatperiod.value < 30)
3007 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3008 if (sv_heartbeatperiod.value > 270)
3009 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3011 // make advertising optional and don't advertise singleplayer games, and
3012 // only send a heartbeat as often as the admin wants
3013 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3015 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3016 for (masternum = 0;sv_masters[masternum].name;masternum++)
3017 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3018 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3022 static void Net_Heartbeat_f(void)
3025 NetConn_Heartbeat(2);
3027 Con_Print("No server running, can not heartbeat to master server.\n");
3030 void PrintStats(netconn_t *conn)
3032 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3033 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3035 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3038 void Net_Stats_f(void)
3041 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3042 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3043 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3044 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3045 Con_Printf("packetsSent = %i\n", packetsSent);
3046 Con_Printf("packetsReSent = %i\n", packetsReSent);
3047 Con_Printf("packetsReceived = %i\n", packetsReceived);
3048 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3049 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3050 Con_Print("connections =\n");
3051 for (conn = netconn_list;conn;conn = conn->next)
3055 void Net_Refresh_f(void)
3057 if (m_state != m_slist) {
3058 Con_Print("Sending new requests to master servers\n");
3059 ServerList_QueryList(false, true, false, true);
3060 Con_Print("Listening for replies...\n");
3062 ServerList_QueryList(false, true, false, false);
3065 void Net_Slist_f(void)
3067 ServerList_ResetMasks();
3068 serverlist_sortbyfield = SLIF_PING;
3069 serverlist_sortflags = 0;
3070 if (m_state != m_slist) {
3071 Con_Print("Sending requests to master servers\n");
3072 ServerList_QueryList(true, true, false, true);
3073 Con_Print("Listening for replies...\n");
3075 ServerList_QueryList(true, true, false, false);
3078 void Net_SlistQW_f(void)
3080 ServerList_ResetMasks();
3081 serverlist_sortbyfield = SLIF_PING;
3082 serverlist_sortflags = 0;
3083 if (m_state != m_slist) {
3084 Con_Print("Sending requests to master servers\n");
3085 ServerList_QueryList(true, false, true, true);
3086 serverlist_consoleoutput = true;
3087 Con_Print("Listening for replies...\n");
3089 ServerList_QueryList(true, false, true, false);
3092 void NetConn_Init(void)
3095 lhnetaddress_t tempaddress;
3096 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3097 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3098 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3099 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3100 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3101 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3102 Cvar_RegisterVariable(&rcon_restricted_password);
3103 Cvar_RegisterVariable(&rcon_restricted_commands);
3104 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3105 Cvar_RegisterVariable(&net_slist_queriespersecond);
3106 Cvar_RegisterVariable(&net_slist_queriesperframe);
3107 Cvar_RegisterVariable(&net_slist_timeout);
3108 Cvar_RegisterVariable(&net_slist_maxtries);
3109 Cvar_RegisterVariable(&net_slist_favorites);
3110 Cvar_RegisterVariable(&net_slist_pause);
3111 Cvar_RegisterVariable(&net_messagetimeout);
3112 Cvar_RegisterVariable(&net_connecttimeout);
3113 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3114 Cvar_RegisterVariable(&cl_netlocalping);
3115 Cvar_RegisterVariable(&cl_netpacketloss_send);
3116 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3117 Cvar_RegisterVariable(&hostname);
3118 Cvar_RegisterVariable(&developer_networking);
3119 Cvar_RegisterVariable(&cl_netport);
3120 Cvar_RegisterVariable(&sv_netport);
3121 Cvar_RegisterVariable(&net_address);
3122 Cvar_RegisterVariable(&net_address_ipv6);
3123 Cvar_RegisterVariable(&sv_public);
3124 Cvar_RegisterVariable(&sv_heartbeatperiod);
3125 for (i = 0;sv_masters[i].name;i++)
3126 Cvar_RegisterVariable(&sv_masters[i]);
3127 Cvar_RegisterVariable(&gameversion);
3128 // 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.
3129 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3131 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3133 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3134 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3137 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3139 // 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
3140 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3142 i = atoi(com_argv[i + 1]);
3143 if (i >= 0 && i < 65536)
3145 Con_Printf("-port option used, setting port cvar to %i\n", i);
3146 Cvar_SetValueQuick(&sv_netport, i);
3149 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3153 net_message.data = net_message_buf;
3154 net_message.maxsize = sizeof(net_message_buf);
3155 net_message.cursize = 0;
3159 void NetConn_Shutdown(void)
3161 NetConn_CloseClientPorts();
3162 NetConn_CloseServerPorts();