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) to be sent to querying clients"};
85 static cvar_t gameversion_min = {0, "gameversion_min", "-1", "minimum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
86 static cvar_t gameversion_max = {0, "gameversion_max", "-1", "maximum version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible; if -1, gameversion is used alone"};
87 static cvar_t rcon_restricted_password = {CVAR_PRIVATE, "rcon_restricted_password", "", "password to authenticate rcon commands in restricted mode"};
88 static cvar_t rcon_restricted_commands = {0, "rcon_restricted_commands", "", "allowed commands for rcon when the restricted mode password was used"};
89 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)"};
90 extern cvar_t rcon_secure;
92 /* statistic counters */
93 static int packetsSent = 0;
94 static int packetsReSent = 0;
95 static int packetsReceived = 0;
96 static int receivedDuplicateCount = 0;
97 static int droppedDatagrams = 0;
99 static int unreliableMessagesSent = 0;
100 static int unreliableMessagesReceived = 0;
101 static int reliableMessagesSent = 0;
102 static int reliableMessagesReceived = 0;
104 double masterquerytime = -1000;
105 int masterquerycount = 0;
106 int masterreplycount = 0;
107 int serverquerycount = 0;
108 int serverreplycount = 0;
110 /// this is only false if there are still servers left to query
111 static qboolean serverlist_querysleep = true;
112 static qboolean serverlist_paused = false;
113 /// this is pushed a second or two ahead of realtime whenever a master server
114 /// reply is received, to avoid issuing queries while master replies are still
115 /// flooding in (which would make a mess of the ping times)
116 static double serverlist_querywaittime = 0;
118 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
119 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
121 static int cl_numsockets;
122 static lhnetsocket_t *cl_sockets[16];
123 static int sv_numsockets;
124 static lhnetsocket_t *sv_sockets[16];
126 netconn_t *netconn_list = NULL;
127 mempool_t *netconn_mempool = NULL;
129 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
130 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
131 cvar_t net_address = {0, "net_address", "", "network address to open ipv4 ports on (if empty, use default interfaces)"};
132 cvar_t net_address_ipv6 = {0, "net_address_ipv6", "", "network address to open ipv6 ports on (if empty, use default interfaces)"};
134 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
135 int net_extresponse_count = 0;
136 int net_extresponse_last = 0;
138 // ServerList interface
139 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
140 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
142 serverlist_infofield_t serverlist_sortbyfield;
143 int serverlist_sortflags;
145 int serverlist_viewcount = 0;
146 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
148 int serverlist_cachecount;
149 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
151 qboolean serverlist_consoleoutput;
153 static int nFavorites = 0;
154 static lhnetaddress_t favorites[256];
156 void NetConn_UpdateFavorites(void)
160 p = net_slist_favorites.string;
161 while((size_t) nFavorites < sizeof(favorites) / sizeof(*favorites) && COM_ParseToken_Console(&p))
163 if(LHNETADDRESS_FromString(&favorites[nFavorites], com_token, 26000))
168 /// helper function to insert a value into the viewset
169 /// spare entries will be removed
170 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
173 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
174 i = serverlist_viewcount++;
176 i = SERVERLIST_VIEWLISTSIZE - 1;
179 for( ; i > index ; i-- )
180 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
182 serverlist_viewlist[index] = entry;
185 /// we suppose serverlist_viewcount to be valid, ie > 0
186 static void _ServerList_ViewList_Helper_Remove( int index )
188 serverlist_viewcount--;
189 for( ; index < serverlist_viewcount ; index++ )
190 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
193 /// \returns true if A should be inserted before B
194 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
196 int result = 0; // > 0 if for numbers A > B and for text if A < B
198 if( serverlist_sortflags & SLSF_FAVORITESFIRST )
200 if(A->info.isfavorite != B->info.isfavorite)
201 return A->info.isfavorite;
204 switch( serverlist_sortbyfield ) {
206 result = A->info.ping - B->info.ping;
208 case SLIF_MAXPLAYERS:
209 result = A->info.maxplayers - B->info.maxplayers;
211 case SLIF_NUMPLAYERS:
212 result = A->info.numplayers - B->info.numplayers;
215 result = A->info.numbots - B->info.numbots;
218 result = A->info.numhumans - B->info.numhumans;
221 result = A->info.freeslots - B->info.freeslots;
224 result = A->info.protocol - B->info.protocol;
227 result = strcmp( B->info.cname, A->info.cname );
230 result = strcasecmp( B->info.game, A->info.game );
233 result = strcasecmp( B->info.map, A->info.map );
236 result = strcasecmp( B->info.mod, A->info.mod );
239 result = strcasecmp( B->info.name, A->info.name );
242 result = strcasecmp( B->info.qcstatus, A->info.qcstatus ); // not really THAT useful, though
244 case SLIF_ISFAVORITE:
245 result = !!B->info.isfavorite - !!A->info.isfavorite;
248 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
254 if( serverlist_sortflags & SLSF_DESCENDING )
260 // if the chosen sort key is identical, sort by index
261 // (makes this a stable sort, so that later replies from servers won't
262 // shuffle the servers around when they have the same ping)
266 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
268 // This should actually be done with some intermediate and end-of-function return
280 case SLMO_GREATEREQUAL:
282 case SLMO_NOTCONTAIN:
283 case SLMO_STARTSWITH:
284 case SLMO_NOTSTARTSWITH:
287 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
292 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
295 char bufferA[ 1400 ], bufferB[ 1400 ]; // should be more than enough
296 COM_StringDecolorize(A, 0, bufferA, sizeof(bufferA), false);
297 for (i = 0;i < (int)sizeof(bufferA)-1 && bufferA[i];i++)
298 bufferA[i] = (bufferA[i] >= 'A' && bufferA[i] <= 'Z') ? (bufferA[i] + 'a' - 'A') : bufferA[i];
300 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
301 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
304 // Same here, also using an intermediate & final return would be more appropriate
308 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
309 case SLMO_NOTCONTAIN:
310 return !*bufferB || !strstr( bufferA, bufferB );
311 case SLMO_STARTSWITH:
312 //Con_Printf("startsWith: %s %s\n", bufferA, bufferB);
313 return *bufferB && !memcmp(bufferA, bufferB, strlen(bufferB));
314 case SLMO_NOTSTARTSWITH:
315 return !*bufferB || memcmp(bufferA, bufferB, strlen(bufferB));
317 return strcmp( bufferA, bufferB ) < 0;
319 return strcmp( bufferA, bufferB ) <= 0;
321 return strcmp( bufferA, bufferB ) == 0;
323 return strcmp( bufferA, bufferB ) > 0;
325 return strcmp( bufferA, bufferB ) != 0;
326 case SLMO_GREATEREQUAL:
327 return strcmp( bufferA, bufferB ) >= 0;
329 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
334 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
336 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
338 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
340 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
342 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
344 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
346 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
348 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
350 if( *mask->info.cname
351 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
354 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
357 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
360 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
363 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
365 if( *mask->info.qcstatus
366 && !_ServerList_CompareStr( info->qcstatus, mask->tests[SLIF_QCSTATUS], mask->info.qcstatus ) )
368 if( *mask->info.players
369 && !_ServerList_CompareStr( info->players, mask->tests[SLIF_PLAYERS], mask->info.players ) )
371 if( !_ServerList_CompareInt( info->isfavorite, mask->tests[SLIF_ISFAVORITE], mask->info.isfavorite ))
376 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
378 int start, end, mid, i;
381 // reject incompatible servers
383 entry->info.gameversion != gameversion.integer
386 gameversion_min.integer >= 0 // min/max range set by user/mod?
387 && gameversion_max.integer >= 0
388 && gameversion_min.integer >= entry->info.gameversion // version of server in min/max range?
389 && gameversion_max.integer <= entry->info.gameversion
394 // refresh the "favorite" status
395 entry->info.isfavorite = false;
396 if(LHNETADDRESS_FromString(&addr, entry->info.cname, 26000))
398 for(i = 0; i < nFavorites; ++i)
400 if(LHNETADDRESS_Compare(&addr, &favorites[i]) == 0)
402 entry->info.isfavorite = true;
408 // FIXME: change this to be more readable (...)
409 // now check whether it passes through the masks
410 for( start = 0 ; start < SERVERLIST_ANDMASKCOUNT && serverlist_andmasks[start].active; start++ )
411 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
414 for( start = 0 ; start < SERVERLIST_ORMASKCOUNT && serverlist_ormasks[start].active ; start++ )
415 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
417 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
420 if( !serverlist_viewcount ) {
421 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
424 // ok, insert it, we just need to find out where exactly:
427 // check whether to insert it as new first item
428 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
429 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
431 } // check whether to insert it as new last item
432 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
433 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
437 end = serverlist_viewcount - 1;
438 while( end > start + 1 )
440 mid = (start + end) / 2;
441 // test the item that lies in the middle between start and end
442 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
443 // the item has to be in the upper half
446 // the item has to be in the lower half
449 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
452 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
455 for( i = 0; i < serverlist_viewcount; i++ )
457 if (serverlist_viewlist[i] == entry)
459 _ServerList_ViewList_Helper_Remove(i);
465 void ServerList_RebuildViewList(void)
469 serverlist_viewcount = 0;
470 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
471 serverlist_entry_t *entry = &serverlist_cache[i];
472 // also display entries that are currently being refreshed [11/8/2007 Black]
473 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
474 ServerList_ViewList_Insert( entry );
478 void ServerList_ResetMasks(void)
482 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
483 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
484 // numbots needs to be compared to -1 to always succeed
485 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
486 serverlist_andmasks[i].info.numbots = -1;
487 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
488 serverlist_ormasks[i].info.numbots = -1;
491 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
494 int numplayers = 0, maxplayers = 0;
495 for (i = 0;i < serverlist_cachecount;i++)
497 if (serverlist_cache[i].query == SQS_QUERIED)
499 numplayers += serverlist_cache[i].info.numhumans;
500 maxplayers += serverlist_cache[i].info.maxplayers;
503 *numplayerspointer = numplayers;
504 *maxplayerspointer = maxplayers;
508 static void _ServerList_Test(void)
511 for( i = 0 ; i < 1024 ; i++ ) {
512 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
513 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
514 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
515 serverlist_cache[serverlist_cachecount].finished = true;
516 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 );
517 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
518 serverlist_cachecount++;
523 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
525 masterquerytime = realtime;
526 masterquerycount = 0;
527 masterreplycount = 0;
529 serverquerycount = 0;
530 serverreplycount = 0;
531 serverlist_cachecount = 0;
532 serverlist_viewcount = 0;
534 // refresh all entries
536 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
537 serverlist_entry_t *entry = &serverlist_cache[ n ];
538 entry->query = SQS_REFRESHING;
539 entry->querycounter = 0;
542 serverlist_consoleoutput = consoleoutput;
544 //_ServerList_Test();
546 NetConn_QueryMasters(querydp, queryqw);
551 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
553 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
557 if (cl_netpacketloss_receive.integer)
558 for (i = 0;i < cl_numsockets;i++)
559 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
561 if (developer_networking.integer)
563 char addressstring[128], addressstring2[128];
564 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
567 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
568 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length, addressstring2);
569 Com_HexDumpToConsole((unsigned char *)data, length);
572 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", (void *)mysocket, addressstring, (void *)data, maxlength, (void *)peeraddress, length);
577 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
581 if (cl_netpacketloss_send.integer)
582 for (i = 0;i < cl_numsockets;i++)
583 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
585 ret = LHNET_Write(mysocket, data, length, peeraddress);
586 if (developer_networking.integer)
588 char addressstring[128], addressstring2[128];
589 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
590 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
591 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", (void *)mysocket, addressstring, (void *)data, length, (void *)peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
592 Com_HexDumpToConsole((unsigned char *)data, length);
597 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
599 // note this does not include the trailing NULL because we add that in the parser
600 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
603 qboolean NetConn_CanSend(netconn_t *conn)
605 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
606 conn->outgoing_netgraph[conn->outgoing_packetcounter].time = realtime;
607 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
608 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
609 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes = NETGRAPH_NOPACKET;
610 if (realtime > conn->cleartime)
614 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_CHOKEDPACKET;
619 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
623 // if this packet was supposedly choked, but we find ourselves sending one
624 // anyway, make sure the size counting starts at zero
625 // (this mostly happens on level changes and disconnects and such)
626 if (conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes == NETGRAPH_CHOKEDPACKET)
627 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes = NETGRAPH_NOPACKET;
629 if (protocol == PROTOCOL_QUAKEWORLD)
632 qboolean sendreliable;
634 // note that it is ok to send empty messages to the qw server,
635 // otherwise it won't respond to us at all
637 sendreliable = false;
638 // if the remote side dropped the last reliable message, resend it
639 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
641 // if the reliable transmit buffer is empty, copy the current message out
642 if (!conn->sendMessageLength && conn->message.cursize)
644 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
645 conn->sendMessageLength = conn->message.cursize;
646 SZ_Clear(&conn->message); // clear the message buffer
647 conn->qw.reliable_sequence ^= 1;
650 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
651 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
652 // last received unreliable packet number, and last received reliable packet number (0 or 1)
653 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
655 conn->outgoing_unreliable_sequence++;
656 // client sends qport in every packet
657 if (conn == cls.netcon)
659 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
661 // also update cls.qw_outgoing_sequence
662 cls.qw_outgoing_sequence = conn->outgoing_unreliable_sequence;
664 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
666 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
670 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
672 // add the reliable message if there is one
675 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += conn->sendMessageLength + 28;
676 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
677 packetLen += conn->sendMessageLength;
678 conn->qw.last_reliable_sequence = conn->outgoing_unreliable_sequence;
681 // add the unreliable message if possible
682 if (packetLen + data->cursize <= 1400)
684 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += data->cursize + 28;
685 memcpy(sendbuffer + packetLen, data->data, data->cursize);
686 packetLen += data->cursize;
689 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
692 unreliableMessagesSent++;
694 totallen += packetLen + 28;
698 unsigned int packetLen;
699 unsigned int dataLen;
701 unsigned int *header;
703 // if a reliable message fragment has been lost, send it again
704 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
706 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
708 dataLen = conn->sendMessageLength;
713 dataLen = MAX_PACKETFRAGMENT;
717 packetLen = NET_HEADERSIZE + dataLen;
719 header = (unsigned int *)sendbuffer;
720 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
721 header[1] = BigLong(conn->nq.sendSequence - 1);
722 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
724 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
726 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
728 conn->lastSendTime = realtime;
732 totallen += packetLen + 28;
735 // if we have a new reliable message to send, do so
736 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
738 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
740 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
741 conn->message.overflowed = true;
745 if (developer_networking.integer && conn == cls.netcon)
747 Con_Print("client sending reliable message to server:\n");
748 SZ_HexDumpToConsole(&conn->message);
751 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
752 conn->sendMessageLength = conn->message.cursize;
753 SZ_Clear(&conn->message);
755 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
757 dataLen = conn->sendMessageLength;
762 dataLen = MAX_PACKETFRAGMENT;
766 packetLen = NET_HEADERSIZE + dataLen;
768 header = (unsigned int *)sendbuffer;
769 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
770 header[1] = BigLong(conn->nq.sendSequence);
771 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
773 conn->nq.sendSequence++;
775 conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
777 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
779 conn->lastSendTime = realtime;
781 reliableMessagesSent++;
783 totallen += packetLen + 28;
786 // if we have an unreliable message to send, do so
789 packetLen = NET_HEADERSIZE + data->cursize;
791 if (packetLen > (int)sizeof(sendbuffer))
793 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
797 header = (unsigned int *)sendbuffer;
798 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
799 header[1] = BigLong(conn->outgoing_unreliable_sequence);
800 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
802 conn->outgoing_unreliable_sequence++;
804 conn->outgoing_netgraph[conn->outgoing_packetcounter].unreliablebytes += packetLen + 28;
806 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
809 unreliableMessagesSent++;
811 totallen += packetLen + 28;
815 // delay later packets to obey rate limit
816 if (conn->cleartime < realtime - 0.1)
817 conn->cleartime = realtime - 0.1;
818 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
819 if (conn->cleartime < realtime)
820 conn->cleartime = realtime;
825 qboolean NetConn_HaveClientPorts(void)
827 return !!cl_numsockets;
830 qboolean NetConn_HaveServerPorts(void)
832 return !!sv_numsockets;
835 void NetConn_CloseClientPorts(void)
837 for (;cl_numsockets > 0;cl_numsockets--)
838 if (cl_sockets[cl_numsockets - 1])
839 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
842 void NetConn_OpenClientPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport)
844 lhnetaddress_t address;
847 char addressstring2[1024];
848 if (addressstring && addressstring[0])
849 success = LHNETADDRESS_FromString(&address, addressstring, defaultport);
851 success = LHNETADDRESS_FromPort(&address, addresstype, defaultport);
854 if ((s = LHNET_OpenSocket_Connectionless(&address)))
856 cl_sockets[cl_numsockets++] = s;
857 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
858 Con_Printf("Client opened a socket on address %s\n", addressstring2);
862 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
863 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
867 Con_Printf("Client unable to parse address %s\n", addressstring);
870 void NetConn_OpenClientPorts(void)
873 NetConn_CloseClientPorts();
874 port = bound(0, cl_netport.integer, 65535);
875 if (cl_netport.integer != port)
876 Cvar_SetValueQuick(&cl_netport, port);
878 Con_Printf("Client using an automatically assigned port\n");
880 Con_Printf("Client using port %i\n", port);
881 NetConn_OpenClientPort(NULL, LHNETADDRESSTYPE_LOOP, 2);
882 NetConn_OpenClientPort(net_address.string, LHNETADDRESSTYPE_INET4, port);
883 NetConn_OpenClientPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port);
886 void NetConn_CloseServerPorts(void)
888 for (;sv_numsockets > 0;sv_numsockets--)
889 if (sv_sockets[sv_numsockets - 1])
890 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
893 qboolean NetConn_OpenServerPort(const char *addressstring, lhnetaddresstype_t addresstype, int defaultport, int range)
895 lhnetaddress_t address;
898 char addressstring2[1024];
901 for (port = defaultport; port <= defaultport + range; port++)
903 if (addressstring && addressstring[0])
904 success = LHNETADDRESS_FromString(&address, addressstring, port);
906 success = LHNETADDRESS_FromPort(&address, addresstype, port);
909 if ((s = LHNET_OpenSocket_Connectionless(&address)))
911 sv_sockets[sv_numsockets++] = s;
912 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
913 Con_Printf("Server listening on address %s\n", addressstring2);
918 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
919 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
924 Con_Printf("Server unable to parse address %s\n", addressstring);
925 // if it cant parse one address, it wont be able to parse another for sure
932 void NetConn_OpenServerPorts(int opennetports)
935 NetConn_CloseServerPorts();
936 NetConn_UpdateSockets();
937 port = bound(0, sv_netport.integer, 65535);
940 Con_Printf("Server using port %i\n", port);
941 if (sv_netport.integer != port)
942 Cvar_SetValueQuick(&sv_netport, port);
943 if (cls.state != ca_dedicated)
944 NetConn_OpenServerPort(NULL, LHNETADDRESSTYPE_LOOP, 1, 1);
947 qboolean ip4success = NetConn_OpenServerPort(net_address.string, LHNETADDRESSTYPE_INET4, port, 100);
948 NetConn_OpenServerPort(net_address_ipv6.string, LHNETADDRESSTYPE_INET6, port, ip4success ? 1 : 100);
950 if (sv_numsockets == 0)
951 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
954 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
956 int i, a = LHNETADDRESS_GetAddressType(address);
957 for (i = 0;i < cl_numsockets;i++)
958 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
959 return cl_sockets[i];
963 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
965 int i, a = LHNETADDRESS_GetAddressType(address);
966 for (i = 0;i < sv_numsockets;i++)
967 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
968 return sv_sockets[i];
972 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
975 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
976 conn->mysocket = mysocket;
977 conn->peeraddress = *peeraddress;
978 conn->lastMessageTime = realtime;
979 conn->message.data = conn->messagedata;
980 conn->message.maxsize = sizeof(conn->messagedata);
981 conn->message.cursize = 0;
982 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
983 // reduce effectiveness of connection request floods
984 conn->timeout = realtime + net_connecttimeout.value;
985 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
986 conn->next = netconn_list;
991 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
992 void NetConn_Close(netconn_t *conn)
995 // remove connection from list
997 // allow the client to reconnect immediately
998 NetConn_ClearConnectFlood(&(conn->peeraddress));
1000 if (conn == netconn_list)
1001 netconn_list = conn->next;
1004 for (c = netconn_list;c;c = c->next)
1006 if (c->next == conn)
1008 c->next = conn->next;
1012 // not found in list, we'll avoid crashing here...
1020 static int clientport = -1;
1021 static int clientport2 = -1;
1022 static int hostport = -1;
1023 void NetConn_UpdateSockets(void)
1025 if (cls.state != ca_dedicated)
1027 if (clientport2 != cl_netport.integer)
1029 clientport2 = cl_netport.integer;
1030 if (cls.state == ca_connected)
1031 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
1033 if (cls.state == ca_disconnected && clientport != clientport2)
1035 clientport = clientport2;
1036 NetConn_CloseClientPorts();
1038 if (cl_numsockets == 0)
1039 NetConn_OpenClientPorts();
1042 if (hostport != sv_netport.integer)
1044 hostport = sv_netport.integer;
1046 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
1050 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
1052 int originallength = length;
1056 if (protocol == PROTOCOL_QUAKEWORLD)
1058 int sequence, sequence_ack;
1059 int reliable_ack, reliable_message;
1063 sequence = LittleLong(*((int *)(data + 0)));
1064 sequence_ack = LittleLong(*((int *)(data + 4)));
1068 if (conn != cls.netcon)
1073 // 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?)
1074 qport = LittleShort(*((int *)(data + 8)));
1080 reliable_message = (sequence >> 31) & 1;
1081 reliable_ack = (sequence_ack >> 31) & 1;
1082 sequence &= ~(1<<31);
1083 sequence_ack &= ~(1<<31);
1084 if (sequence <= conn->qw.incoming_sequence)
1086 //Con_DPrint("Got a stale datagram\n");
1089 count = sequence - (conn->qw.incoming_sequence + 1);
1092 droppedDatagrams += count;
1093 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1096 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1097 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1098 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1099 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1100 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1103 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1104 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1105 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1106 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1107 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1108 if (reliable_ack == conn->qw.reliable_sequence)
1110 // received, now we will be able to send another reliable message
1111 conn->sendMessageLength = 0;
1112 reliableMessagesReceived++;
1114 conn->qw.incoming_sequence = sequence;
1115 if (conn == cls.netcon)
1116 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1117 conn->qw.incoming_acknowledged = sequence_ack;
1118 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1119 if (reliable_message)
1120 conn->qw.incoming_reliable_sequence ^= 1;
1121 conn->lastMessageTime = realtime;
1122 conn->timeout = realtime + newtimeout;
1123 unreliableMessagesReceived++;
1124 SZ_Clear(&net_message);
1125 SZ_Write(&net_message, data, length);
1133 unsigned int sequence;
1136 qlength = (unsigned int)BigLong(((int *)data)[0]);
1137 flags = qlength & ~NETFLAG_LENGTH_MASK;
1138 qlength &= NETFLAG_LENGTH_MASK;
1139 // control packets were already handled
1140 if (!(flags & NETFLAG_CTL) && qlength == length)
1142 sequence = BigLong(((int *)data)[1]);
1146 if (flags & NETFLAG_UNRELIABLE)
1148 if (sequence >= conn->nq.unreliableReceiveSequence)
1150 if (sequence > conn->nq.unreliableReceiveSequence)
1152 count = sequence - conn->nq.unreliableReceiveSequence;
1153 droppedDatagrams += count;
1154 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1157 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1158 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1159 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = NETGRAPH_LOSTPACKET;
1160 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1161 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1164 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1165 conn->incoming_netgraph[conn->incoming_packetcounter].time = realtime;
1166 conn->incoming_netgraph[conn->incoming_packetcounter].unreliablebytes = originallength + 28;
1167 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes = NETGRAPH_NOPACKET;
1168 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes = NETGRAPH_NOPACKET;
1169 conn->nq.unreliableReceiveSequence = sequence + 1;
1170 conn->lastMessageTime = realtime;
1171 conn->timeout = realtime + newtimeout;
1172 unreliableMessagesReceived++;
1175 SZ_Clear(&net_message);
1176 SZ_Write(&net_message, data, length);
1182 // Con_DPrint("Got a stale datagram\n");
1185 else if (flags & NETFLAG_ACK)
1187 conn->incoming_netgraph[conn->incoming_packetcounter].ackbytes += originallength + 28;
1188 if (sequence == (conn->nq.sendSequence - 1))
1190 if (sequence == conn->nq.ackSequence)
1192 conn->nq.ackSequence++;
1193 if (conn->nq.ackSequence != conn->nq.sendSequence)
1194 Con_DPrint("ack sequencing error\n");
1195 conn->lastMessageTime = realtime;
1196 conn->timeout = realtime + newtimeout;
1197 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1199 unsigned int packetLen;
1200 unsigned int dataLen;
1202 unsigned int *header;
1204 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1205 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1207 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1209 dataLen = conn->sendMessageLength;
1214 dataLen = MAX_PACKETFRAGMENT;
1218 packetLen = NET_HEADERSIZE + dataLen;
1220 header = (unsigned int *)sendbuffer;
1221 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1222 header[1] = BigLong(conn->nq.sendSequence);
1223 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1225 conn->nq.sendSequence++;
1227 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1229 conn->lastSendTime = realtime;
1234 conn->sendMessageLength = 0;
1237 // Con_DPrint("Duplicate ACK received\n");
1240 // Con_DPrint("Stale ACK received\n");
1243 else if (flags & NETFLAG_DATA)
1245 unsigned int temppacket[2];
1246 conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes += originallength + 28;
1247 conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes += 8 + 28;
1248 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1249 temppacket[1] = BigLong(sequence);
1250 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1251 if (sequence == conn->nq.receiveSequence)
1253 conn->lastMessageTime = realtime;
1254 conn->timeout = realtime + newtimeout;
1255 conn->nq.receiveSequence++;
1256 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1257 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1258 conn->receiveMessageLength += length;
1260 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1261 "Dropping the message!\n", sequence );
1262 conn->receiveMessageLength = 0;
1265 if (flags & NETFLAG_EOM)
1267 reliableMessagesReceived++;
1268 length = conn->receiveMessageLength;
1269 conn->receiveMessageLength = 0;
1272 SZ_Clear(&net_message);
1273 SZ_Write(&net_message, conn->receiveMessage, length);
1280 receivedDuplicateCount++;
1288 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1290 cls.connect_trying = false;
1291 M_Update_Return_Reason("");
1292 // the connection request succeeded, stop current connection and set up a new connection
1294 // if we're connecting to a remote server, shut down any local server
1295 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1296 Host_ShutdownServer ();
1297 // allocate a net connection to keep track of things
1298 cls.netcon = NetConn_Open(mysocket, peeraddress);
1299 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1300 key_dest = key_game;
1302 cls.demonum = -1; // not in the demo loop now
1303 cls.state = ca_connected;
1304 cls.signon = 0; // need all the signon messages before playing
1305 cls.protocol = initialprotocol;
1306 // reset move sequence numbering on this new connection
1307 cls.servermovesequence = 0;
1308 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1309 Cmd_ForwardStringToServer("new");
1310 if (cls.protocol == PROTOCOL_QUAKE)
1312 // write a keepalive (clc_nop) as it seems to greatly improve the
1313 // chances of connecting to a netquake server
1315 unsigned char buf[4];
1316 memset(&msg, 0, sizeof(msg));
1318 msg.maxsize = sizeof(buf);
1319 MSG_WriteChar(&msg, clc_nop);
1320 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1324 int NetConn_IsLocalGame(void)
1326 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1331 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1335 serverlist_entry_t *entry = NULL;
1337 // search the cache for this server and update it
1338 for (n = 0;n < serverlist_cachecount;n++) {
1339 entry = &serverlist_cache[ n ];
1340 if (!strcmp(addressstring, entry->info.cname))
1344 if (n == serverlist_cachecount)
1346 // LAN search doesnt require an answer from the master server so we wont
1347 // know the ping nor will it be initialized already...
1350 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1353 entry = &serverlist_cache[n];
1355 memset(entry, 0, sizeof(*entry));
1356 // store the data the engine cares about (address and ping)
1357 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1358 entry->info.ping = 100000;
1359 entry->querytime = realtime;
1360 // if not in the slist menu we should print the server to console
1361 if (serverlist_consoleoutput)
1362 Con_Printf("querying %s\n", addressstring);
1363 ++serverlist_cachecount;
1365 // if this is the first reply from this server, count it as having replied
1366 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1367 pingtime = bound(0, pingtime, 9999);
1368 if (entry->query == SQS_REFRESHING) {
1369 entry->info.ping = pingtime;
1370 entry->query = SQS_QUERIED;
1372 // convert to unsigned to catch the -1
1373 // 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]
1374 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1378 // other server info is updated by the caller
1382 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1384 serverlist_entry_t *entry = &serverlist_cache[n];
1385 serverlist_info_t *info = &entry->info;
1386 // update description strings for engine menu and console output
1387 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);
1388 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game,
1390 info->gameversion != gameversion.integer
1393 gameversion_min.integer >= 0 // min/max range set by user/mod?
1394 && gameversion_max.integer >= 0
1395 && gameversion_min.integer >= info->gameversion // version of server in min/max range?
1396 && gameversion_max.integer <= info->gameversion
1399 info->mod, info->map);
1400 if (entry->query == SQS_QUERIED)
1402 if(!serverlist_paused)
1403 ServerList_ViewList_Remove(entry);
1405 // if not in the slist menu we should print the server to console (if wanted)
1406 else if( serverlist_consoleoutput )
1407 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1408 // and finally, update the view set
1409 if(!serverlist_paused)
1410 ServerList_ViewList_Insert( entry );
1411 // update the entry's state
1412 serverlist_cache[n].query = SQS_QUERIED;
1415 // returns true, if it's sensible to continue the processing
1416 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring, qboolean isfavorite ) {
1418 serverlist_entry_t *entry;
1420 // ignore the rest of the message if the serverlist is full
1421 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1423 // also ignore it if we have already queried it (other master server response)
1424 for( n = 0 ; n < serverlist_cachecount ; n++ )
1425 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1428 entry = &serverlist_cache[n];
1430 if( n < serverlist_cachecount ) {
1431 // the entry has already been queried once or
1435 memset(entry, 0, sizeof(entry));
1436 entry->protocol = protocol;
1437 // store the data the engine cares about (address and ping)
1438 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1440 entry->info.isfavorite = isfavorite;
1442 // no, then reset the ping right away
1443 entry->info.ping = -1;
1444 // we also want to increase the serverlist_cachecount then
1445 serverlist_cachecount++;
1448 entry->query = SQS_QUERYING;
1453 static void NetConn_ClientParsePacket_ServerList_ParseDPList(lhnetaddress_t *senderaddress, const unsigned char *data, int length, qboolean isextended)
1456 if (serverlist_consoleoutput)
1457 Con_Printf("received DarkPlaces %sserver list...\n", isextended ? "extended " : "");
1460 char ipstring [128];
1463 if (data[0] == '\\')
1465 unsigned short port = data[5] * 256 + data[6];
1467 if (port != 0 && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF))
1468 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%hu", data[1], data[2], data[3], data[4], port);
1470 // move on to next address in packet
1475 else if (data[0] == '/' && isextended && length >= 19)
1477 unsigned short port = data[17] * 256 + data[18];
1483 /// \TODO: make some basic checks of the IP address (broadcast, ...)
1485 ifname = LHNETADDRESS_GetInterfaceName(senderaddress);
1488 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x%%%s]:%hu",
1489 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1490 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1495 dpsnprintf (ipstring, sizeof (ipstring), "[%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x]:%hu",
1496 data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8],
1497 data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16],
1502 // move on to next address in packet
1508 Con_Print("Error while parsing the server list\n");
1512 if (serverlist_consoleoutput && developer_networking.integer)
1513 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1515 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring, false ) ) {
1521 // begin or resume serverlist queries
1522 serverlist_querysleep = false;
1523 serverlist_querywaittime = realtime + 3;
1526 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1528 qboolean fromserver;
1529 int ret, c, control;
1531 char *string, addressstring2[128], ipstring[32];
1532 char stringbuf[16384];
1534 // quakeworld ingame packet
1535 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1537 // convert the address to a string incase we need it
1538 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1540 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1542 // received a command string - strip off the packaging and put it
1543 // into our string buffer with NULL termination
1546 length = min(length, (int)sizeof(stringbuf) - 1);
1547 memcpy(stringbuf, data, length);
1548 stringbuf[length] = 0;
1551 if (developer_networking.integer)
1553 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1554 Com_HexDumpToConsole(data, length);
1557 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.rcon_trying)
1560 for (i = 0;i < MAX_RCONS;i++)
1561 if(cls.rcon_commands[i][0])
1562 if (!LHNETADDRESS_Compare(peeraddress, &cls.rcon_addresses[i]))
1568 dpsnprintf(argbuf, sizeof(argbuf), "%s %s", string + 10, cls.rcon_commands[i]);
1569 memcpy(buf, "\377\377\377\377srcon HMAC-MD4 CHALLENGE ", 29);
1570 if(HMAC_MDFOUR_16BYTES((unsigned char *) (buf + 29), (unsigned char *) argbuf, strlen(argbuf), (unsigned char *) rcon_password.string, strlen(rcon_password.string)))
1573 strlcpy(buf + 46, argbuf, sizeof(buf) - 46);
1574 NetConn_Write(mysocket, buf, 46 + strlen(buf + 46), peeraddress);
1575 cls.rcon_commands[i][0] = 0;
1577 return true; // we used up the challenge, so we can't use this oen for connecting now anyway
1581 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1583 // darkplaces or quake3
1584 char protocolnames[1400];
1585 Protocol_Names(protocolnames, sizeof(protocolnames));
1586 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1587 M_Update_Return_Reason("Got challenge response");
1588 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1589 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1590 // TODO: add userinfo stuff here instead of using NQ commands?
1591 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1594 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1596 // darkplaces or quake3
1597 M_Update_Return_Reason("Accepted");
1598 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1601 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1603 char rejectreason[32];
1604 cls.connect_trying = false;
1606 length = min(length - 7, (int)sizeof(rejectreason) - 1);
1607 memcpy(rejectreason, string, length);
1608 rejectreason[length] = 0;
1609 M_Update_Return_Reason(rejectreason);
1612 if (length >= 15 && !memcmp(string, "statusResponse\x0A", 15))
1614 serverlist_info_t *info;
1619 // search the cache for this server and update it
1620 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1624 info = &serverlist_cache[n].info;
1629 info->qcstatus[0] = 0;
1630 info->players[0] = 0;
1631 info->protocol = -1;
1632 info->numplayers = 0;
1634 info->maxplayers = 0;
1635 info->gameversion = 0;
1637 p = strchr(string, '\n');
1640 *p = 0; // cut off the string there
1644 Con_Printf("statusResponse without players block?\n");
1646 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1647 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1648 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1649 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1650 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1651 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1652 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1653 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1654 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1655 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1656 if (p != NULL) strlcpy(info->players, p, sizeof(info->players));
1657 info->numhumans = info->numplayers - max(0, info->numbots);
1658 info->freeslots = info->maxplayers - info->numplayers;
1660 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1664 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1666 serverlist_info_t *info;
1670 // search the cache for this server and update it
1671 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1675 info = &serverlist_cache[n].info;
1680 info->qcstatus[0] = 0;
1681 info->players[0] = 0;
1682 info->protocol = -1;
1683 info->numplayers = 0;
1685 info->maxplayers = 0;
1686 info->gameversion = 0;
1688 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1689 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1690 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1691 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1692 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1693 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1694 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1695 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1696 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1697 if ((s = SearchInfostring(string, "qcstatus" )) != NULL) strlcpy(info->qcstatus, s, sizeof(info->qcstatus));
1698 info->numhumans = info->numplayers - max(0, info->numbots);
1699 info->freeslots = info->maxplayers - info->numplayers;
1701 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1705 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1707 // Extract the IP addresses
1710 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, false);
1713 if (!strncmp(string, "getserversExtResponse", 21) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1715 // Extract the IP addresses
1718 NetConn_ClientParsePacket_ServerList_ParseDPList(peeraddress, data, length, true);
1721 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1723 // Extract the IP addresses
1727 if (serverlist_consoleoutput)
1728 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1729 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1731 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1732 if (serverlist_consoleoutput && developer_networking.integer)
1733 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1735 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring, false ) ) {
1739 // move on to next address in packet
1743 // begin or resume serverlist queries
1744 serverlist_querysleep = false;
1745 serverlist_querywaittime = realtime + 3;
1748 if (!strncmp(string, "extResponse ", 12))
1750 ++net_extresponse_count;
1751 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1752 net_extresponse_count = NET_EXTRESPONSE_MAX;
1753 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1754 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1757 if (!strncmp(string, "ping", 4))
1759 if (developer.integer >= 10)
1760 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1761 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1764 if (!strncmp(string, "ack", 3))
1766 // QuakeWorld compatibility
1767 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1769 // challenge message
1770 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1771 M_Update_Return_Reason("Got QuakeWorld challenge response");
1772 cls.qw_qport = qport.integer;
1773 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1774 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1775 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1778 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1781 M_Update_Return_Reason("QuakeWorld Accepted");
1782 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1785 if (length > 2 && !memcmp(string, "n\\", 2))
1787 serverlist_info_t *info;
1791 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1792 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1795 // search the cache for this server and update it
1796 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1800 info = &serverlist_cache[n].info;
1801 strlcpy(info->game, "QuakeWorld", sizeof(info->game));
1802 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1803 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1804 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1806 info->numplayers = 0; // updated below
1807 info->numhumans = 0; // updated below
1808 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1809 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1811 // count active players on server
1812 // (we could gather more info, but we're just after the number)
1813 s = strchr(string, '\n');
1817 while (s < string + length)
1819 for (;s < string + length && *s != '\n';s++)
1821 if (s >= string + length)
1829 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1833 if (string[0] == 'n')
1836 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1838 // we may not have liked the packet, but it was a command packet, so
1839 // we're done processing this packet now
1842 // quakeworld ingame packet
1843 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1846 CL_ParseServerMessage();
1849 // netquake control packets, supported for compatibility only
1850 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1853 serverlist_info_t *info;
1857 SZ_Clear(&net_message);
1858 SZ_Write(&net_message, data, length);
1864 if (developer.integer >= 10)
1865 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1866 if (cls.connect_trying)
1868 lhnetaddress_t clientportaddress;
1869 clientportaddress = *peeraddress;
1870 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1871 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1872 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1873 M_Update_Return_Reason("Accepted");
1874 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1878 if (developer.integer >= 10)
1879 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1880 cls.connect_trying = false;
1881 M_Update_Return_Reason((char *)MSG_ReadString());
1883 case CCREP_SERVER_INFO:
1884 if (developer.integer >= 10)
1885 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1886 // LordHavoc: because the quake server may report weird addresses
1887 // we just ignore it and keep the real address
1889 // search the cache for this server and update it
1890 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1894 info = &serverlist_cache[n].info;
1895 strlcpy(info->game, "Quake", sizeof(info->game));
1896 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1897 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1898 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1899 info->numplayers = MSG_ReadByte();
1900 info->maxplayers = MSG_ReadByte();
1901 info->protocol = MSG_ReadByte();
1903 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1906 case CCREP_RCON: // RocketGuy: ProQuake rcon support
1907 if (developer.integer >= 10)
1908 Con_Printf("Datagram_ParseConnectionless: received CCREP_RCON from %s.\n", addressstring2);
1910 Con_Printf("%s\n", MSG_ReadString());
1912 case CCREP_PLAYER_INFO:
1913 // we got a CCREP_PLAYER_INFO??
1914 //if (developer.integer >= 10)
1915 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1917 case CCREP_RULE_INFO:
1918 // we got a CCREP_RULE_INFO??
1919 //if (developer.integer >= 10)
1920 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1925 SZ_Clear(&net_message);
1926 // we may not have liked the packet, but it was a valid control
1927 // packet, so we're done processing this packet now
1931 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1932 CL_ParseServerMessage();
1936 void NetConn_QueryQueueFrame(void)
1942 static double querycounter = 0;
1944 if(!net_slist_pause.integer && serverlist_paused)
1945 ServerList_RebuildViewList();
1946 serverlist_paused = net_slist_pause.integer != 0;
1948 if (serverlist_querysleep)
1951 // apply a cool down time after master server replies,
1952 // to avoid messing up the ping times on the servers
1953 if (serverlist_querywaittime > realtime)
1956 // each time querycounter reaches 1.0 issue a query
1957 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1958 maxqueries = (int)querycounter;
1959 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1960 querycounter -= maxqueries;
1962 if( maxqueries == 0 ) {
1966 // scan serverlist and issue queries as needed
1967 serverlist_querysleep = true;
1969 timeouttime = realtime - net_slist_timeout.value;
1970 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1972 serverlist_entry_t *entry = &serverlist_cache[ index ];
1973 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1978 serverlist_querysleep = false;
1979 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1984 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1986 lhnetaddress_t address;
1989 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1990 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1992 for (socket = 0; socket < cl_numsockets ; socket++)
1993 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1997 for (socket = 0; socket < cl_numsockets ; socket++)
1998 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getstatus", &address);
2001 // update the entry fields
2002 entry->querytime = realtime;
2003 entry->querycounter++;
2005 // if not in the slist menu we should print the server to console
2006 if (serverlist_consoleoutput)
2007 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
2013 // have we tried to refresh this server?
2014 if( entry->query == SQS_REFRESHING ) {
2015 // yes, so update the reply count (since its not responding anymore)
2017 if(!serverlist_paused)
2018 ServerList_ViewList_Remove(entry);
2020 entry->query = SQS_TIMEDOUT;
2025 void NetConn_ClientFrame(void)
2028 lhnetaddress_t peeraddress;
2029 NetConn_UpdateSockets();
2030 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
2032 if (cls.connect_remainingtries == 0)
2033 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
2034 cls.connect_nextsendtime = realtime + 1;
2035 cls.connect_remainingtries--;
2036 if (cls.connect_remainingtries <= -10)
2038 cls.connect_trying = false;
2039 M_Update_Return_Reason("Connect: Failed");
2042 // try challenge first (newer DP server or QW)
2043 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
2044 // then try netquake as a fallback (old server, or netquake)
2045 SZ_Clear(&net_message);
2046 // save space for the header, filled in later
2047 MSG_WriteLong(&net_message, 0);
2048 MSG_WriteByte(&net_message, CCREQ_CONNECT);
2049 MSG_WriteString(&net_message, "QUAKE");
2050 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2051 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2052 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
2053 SZ_Clear(&net_message);
2055 for (i = 0;i < cl_numsockets;i++)
2056 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2057 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
2058 NetConn_QueryQueueFrame();
2059 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
2061 Con_Print("Connection timed out\n");
2063 Host_ShutdownServer ();
2067 #define MAX_CHALLENGES 128
2070 lhnetaddress_t address;
2074 challenge[MAX_CHALLENGES];
2076 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
2080 for (i = 0;i < bufferlength - 1;i++)
2084 c = rand () % (127 - 33) + 33;
2085 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
2091 /// (div0) build the full response only if possible; better a getinfo response than no response at all if getstatus won't fit
2092 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
2095 unsigned int nb_clients = 0, nb_bots = 0, i;
2101 // How many clients are there?
2102 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2104 if (svs.clients[i].active)
2107 if (!svs.clients[i].netconnection)
2113 if(prog->globaloffsets.worldstatus >= 0)
2115 const char *str = PRVM_G_STRING(prog->globaloffsets.worldstatus);
2121 for(q = str; *q; ++q)
2122 if(*q != '\\' && *q != '\n')
2128 /// \TODO: we should add more information for the full status string
2129 length = dpsnprintf(out_msg, out_size,
2130 "\377\377\377\377%s\x0A"
2131 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
2132 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
2136 fullstatus ? "statusResponse" : "infoResponse",
2137 gamename, com_modname, gameversion.integer, svs.maxclients,
2138 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
2139 *qcstatus ? "\\qcstatus\\" : "", qcstatus,
2140 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
2141 fullstatus ? "\n" : "");
2143 // Make sure it fits in the buffer
2153 savelength = length;
2155 ptr = out_msg + length;
2156 left = (int)out_size - length;
2158 for (i = 0;i < (unsigned int)svs.maxclients;i++)
2160 client_t *cl = &svs.clients[i];
2163 int nameind, cleanind, pingvalue;
2165 char cleanname [sizeof(cl->name)];
2167 // Remove all characters '"' and '\' in the player name
2172 curchar = cl->name[nameind++];
2173 if (curchar != '"' && curchar != '\\')
2175 cleanname[cleanind++] = curchar;
2176 if (cleanind == sizeof(cleanname) - 1)
2179 } while (curchar != '\0');
2180 cleanname[cleanind] = 0; // cleanind is always a valid index even at this point
2182 pingvalue = (int)(cl->ping * 1000.0f);
2183 if(cl->netconnection)
2184 pingvalue = bound(1, pingvalue, 9999);
2189 if(prog->fieldoffsets.clientstatus >= 0)
2191 const char *str = PRVM_E_STRING(PRVM_EDICT_NUM(i + 1), prog->fieldoffsets.clientstatus);
2197 for(q = str; *q && p != qcstatus + sizeof(qcstatus) - 1; ++q)
2198 if(*q != '\\' && *q != '"' && !ISWHITESPACE(*q))
2204 if ((gamemode == GAME_NEXUIZ) && (teamplay.integer > 0))
2206 if(cl->frags == -666) // spectator
2207 strlcpy(teambuf, " 0", sizeof(teambuf));
2208 else if(cl->colors == 0x44) // red team
2209 strlcpy(teambuf, " 1", sizeof(teambuf));
2210 else if(cl->colors == 0xDD) // blue team
2211 strlcpy(teambuf, " 2", sizeof(teambuf));
2212 else if(cl->colors == 0xCC) // yellow team
2213 strlcpy(teambuf, " 3", sizeof(teambuf));
2214 else if(cl->colors == 0x99) // pink team
2215 strlcpy(teambuf, " 4", sizeof(teambuf));
2217 strlcpy(teambuf, " 0", sizeof(teambuf));
2222 // note: team number is inserted according to SoF2 protocol
2224 length = dpsnprintf(ptr, left, "%s %d%s \"%s\"\n",
2230 length = dpsnprintf(ptr, left, "%d %d%s \"%s\"\n",
2239 // turn it into an infoResponse!
2240 out_msg[savelength] = 0;
2241 memcpy(out_msg + 4, "infoResponse\x0A", 13);
2242 memmove(out_msg + 17, out_msg + 19, savelength - 19);
2259 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
2261 int floodslotnum, bestfloodslotnum;
2262 double bestfloodtime;
2263 lhnetaddress_t noportpeeraddress;
2264 // see if this is a connect flood
2265 noportpeeraddress = *peeraddress;
2266 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2267 bestfloodslotnum = 0;
2268 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
2269 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2271 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
2273 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
2274 bestfloodslotnum = floodslotnum;
2276 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2278 // this address matches an ongoing flood address
2279 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
2281 // renew the ban on this address so it does not expire
2282 // until the flood has subsided
2283 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
2284 //Con_Printf("Flood detected!\n");
2287 // the flood appears to have subsided, so allow this
2288 bestfloodslotnum = floodslotnum; // reuse the same slot
2292 // begin a new timeout on this address
2293 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
2294 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
2295 //Con_Printf("Flood detection initiated!\n");
2299 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
2302 lhnetaddress_t noportpeeraddress;
2303 // see if this is a connect flood
2304 noportpeeraddress = *peeraddress;
2305 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
2306 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
2308 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
2310 // this address matches an ongoing flood address
2312 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
2313 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
2314 //Con_Printf("Flood cleared!\n");
2319 typedef qboolean (*rcon_matchfunc_t) (lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen);
2321 qboolean hmac_mdfour_time_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2326 t1 = (long) time(NULL);
2327 t2 = strtol(s, NULL, 0);
2328 if(abs(t1 - t2) > rcon_secure_maxdiff.integer)
2331 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2334 return !memcmp(mdfourbuf, hash, 16);
2337 qboolean hmac_mdfour_challenge_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2342 if(slen < (int)(sizeof(challenge[0].string)) - 1)
2345 // validate the challenge
2346 for (i = 0;i < MAX_CHALLENGES;i++)
2347 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strncmp(challenge[i].string, s, sizeof(challenge[0].string) - 1))
2349 // if the challenge is not recognized, drop the packet
2350 if (i == MAX_CHALLENGES)
2353 if(!HMAC_MDFOUR_16BYTES((unsigned char *) mdfourbuf, (unsigned char *) s, slen, (unsigned char *) password, strlen(password)))
2356 if(memcmp(mdfourbuf, hash, 16))
2359 // unmark challenge to prevent replay attacks
2360 // FIXME as there is currently no unmark facility, let's invalidate it
2361 // as much as possible
2362 challenge[i].string[0] = '\\'; // not allowed in infostrings, so connects cannot match
2363 NetConn_BuildChallengeString(challenge[i].string + 1, sizeof(challenge[i].string) - 1);
2364 challenge[i].time = 0;
2365 LHNETADDRESS_FromString(&challenge[i].address, "local:42", 42); // no rcon will come from there for sure
2366 challenge[i].address = *peeraddress;
2371 qboolean plaintext_matching(lhnetaddress_t *peeraddress, const char *password, const char *hash, const char *s, int slen)
2373 return !strcmp(password, hash);
2376 /// returns a string describing the user level, or NULL for auth failure
2377 const char *RCon_Authenticate(lhnetaddress_t *peeraddress, const char *password, const char *s, const char *endpos, rcon_matchfunc_t comparator, const char *cs, int cslen)
2382 if(comparator(peeraddress, rcon_password.string, password, cs, cslen))
2385 if(!comparator(peeraddress, rcon_restricted_password.string, password, cs, cslen))
2388 for(text = s; text != endpos; ++text)
2389 if((signed char) *text > 0 && ((signed char) *text < (signed char) ' ' || *text == ';'))
2390 return NULL; // block possible exploits against the parser/alias expansion
2394 size_t l = strlen(s);
2397 hasquotes = (strchr(s, '"') != NULL);
2398 // sorry, we can't allow these substrings in wildcard expressions,
2399 // as they can mess with the argument counts
2400 text = rcon_restricted_commands.string;
2401 while(COM_ParseToken_Console(&text))
2403 // com_token now contains a pattern to check for...
2404 if(strchr(com_token, '*') || strchr(com_token, '?')) // wildcard expression, * can only match a SINGLE argument
2407 if(matchpattern_with_separator(s, com_token, true, " ", true)) // note how we excluded tab, newline etc. above
2410 else if(strchr(com_token, ' ')) // multi-arg expression? must match in whole
2412 if(!strcmp(com_token, s))
2415 else // single-arg expression? must match the beginning of the command
2417 if(!strcmp(com_token, s))
2419 if(!memcmp(va("%s ", com_token), s, strlen(com_token) + 1))
2423 // if we got here, nothing matched!
2430 return "restricted rcon";
2433 void RCon_Execute(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, const char *addressstring2, const char *userlevel, const char *s, const char *endpos)
2437 // looks like a legitimate rcon command with the correct password
2438 const char *s_ptr = s;
2439 Con_Printf("server received %s command from %s: ", userlevel, host_client ? host_client->name : addressstring2);
2440 while(s_ptr != endpos)
2442 size_t l = strlen(s_ptr);
2444 Con_Printf(" %s;", s_ptr);
2449 if (!host_client || !host_client->netconnection || LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2450 Con_Rcon_Redirect_Init(mysocket, peeraddress);
2453 size_t l = strlen(s);
2456 client_t *host_client_save = host_client;
2457 Cmd_ExecuteString(s, src_command);
2458 host_client = host_client_save;
2459 // in case it is a command that changes host_client (like restart)
2463 Con_Rcon_Redirect_End();
2467 Con_Printf("server denied rcon access to %s\n", host_client ? host_client->name : addressstring2);
2471 extern void SV_SendServerinfo (client_t *client);
2472 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
2474 int i, ret, clientnum, best;
2477 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
2478 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
2483 // convert the address to a string incase we need it
2484 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
2486 // see if we can identify the sender as a local player
2487 // (this is necessary for rcon to send a reliable reply if the client is
2488 // actually on the server, not sending remotely)
2489 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2490 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
2492 if (i == svs.maxclients)
2495 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
2497 // received a command string - strip off the packaging and put it
2498 // into our string buffer with NULL termination
2501 length = min(length, (int)sizeof(stringbuf) - 1);
2502 memcpy(stringbuf, data, length);
2503 stringbuf[length] = 0;
2506 if (developer.integer >= 10)
2508 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2509 Com_HexDumpToConsole(data, length);
2512 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2514 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2516 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2518 if (besttime > challenge[i].time)
2519 besttime = challenge[best = i].time;
2521 // if we did not find an exact match, choose the oldest and
2522 // update address and string
2523 if (i == MAX_CHALLENGES)
2526 challenge[i].address = *peeraddress;
2527 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2529 challenge[i].time = realtime;
2530 // send the challenge
2531 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2534 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2539 if (!(s = SearchInfostring(string, "challenge")))
2541 // validate the challenge
2542 for (i = 0;i < MAX_CHALLENGES;i++)
2543 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2545 // if the challenge is not recognized, drop the packet
2546 if (i == MAX_CHALLENGES)
2549 // check engine protocol
2550 if(!(s = SearchInfostring(string, "protocol")) || strcmp(s, "darkplaces 3"))
2552 if (developer.integer >= 10)
2553 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2554 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2558 // see if this is a duplicate connection request or a disconnected
2559 // client who is rejoining to the same client slot
2560 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2562 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2564 // this is a known client...
2565 if (client->spawned)
2567 // client crashed and is coming back,
2568 // keep their stuff intact
2569 if (developer.integer >= 10)
2570 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2571 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2573 SV_SendServerinfo(client);
2578 // client is still trying to connect,
2579 // so we send a duplicate reply
2580 if (developer.integer >= 10)
2581 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2582 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2588 if (NetConn_PreventConnectFlood(peeraddress))
2591 // find an empty client slot for this new client
2592 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2595 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2597 // allocated connection
2598 if (developer.integer >= 10)
2599 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2600 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2601 // now set up the client
2603 SV_ConnectClient(clientnum, conn);
2605 NetConn_Heartbeat(1);
2610 // no empty slots found - server is full
2611 if (developer.integer >= 10)
2612 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2613 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2617 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2619 const char *challenge = NULL;
2621 // If there was a challenge in the getinfo message
2622 if (length > 8 && string[7] == ' ')
2623 challenge = string + 8;
2625 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2627 if (developer.integer >= 10)
2628 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2629 NetConn_WriteString(mysocket, response, peeraddress);
2633 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2635 const char *challenge = NULL;
2637 // If there was a challenge in the getinfo message
2638 if (length > 10 && string[9] == ' ')
2639 challenge = string + 10;
2641 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2643 if (developer.integer >= 10)
2644 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2645 NetConn_WriteString(mysocket, response, peeraddress);
2649 if (length >= 37 && !memcmp(string, "srcon HMAC-MD4 TIME ", 20))
2651 char *password = string + 20;
2652 char *timeval = string + 37;
2653 char *s = strchr(timeval, ' ');
2654 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2655 const char *userlevel;
2657 if(rcon_secure.integer > 1)
2661 return true; // invalid packet
2664 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_time_matching, timeval, endpos - timeval - 1); // not including the appended \0 into the HMAC
2665 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2668 if (length >= 42 && !memcmp(string, "srcon HMAC-MD4 CHALLENGE ", 25))
2670 char *password = string + 25;
2671 char *challenge = string + 42;
2672 char *s = strchr(challenge, ' ');
2673 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2674 const char *userlevel;
2676 return true; // invalid packet
2679 userlevel = RCon_Authenticate(peeraddress, password, s, endpos, hmac_mdfour_challenge_matching, challenge, endpos - challenge - 1); // not including the appended \0 into the HMAC
2680 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2683 if (length >= 5 && !memcmp(string, "rcon ", 5))
2686 char *s = string + 5;
2687 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2690 if(rcon_secure.integer)
2693 for (i = 0;!ISWHITESPACE(*s);s++)
2694 if (i < (int)sizeof(password) - 1)
2696 if(ISWHITESPACE(*s) && s != endpos) // skip leading ugly space
2699 if (!ISWHITESPACE(password[0]))
2701 const char *userlevel = RCon_Authenticate(peeraddress, password, s, endpos, plaintext_matching, NULL, 0);
2702 RCon_Execute(mysocket, peeraddress, addressstring2, userlevel, s, endpos);
2706 if (!strncmp(string, "ping", 4))
2708 if (developer.integer >= 10)
2709 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2710 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2713 if (!strncmp(string, "ack", 3))
2715 // we may not have liked the packet, but it was a command packet, so
2716 // we're done processing this packet now
2719 // netquake control packets, supported for compatibility only, and only
2720 // when running game protocols that are normally served via this connection
2722 // (this protects more modern protocols against being used for
2723 // Quake packet flood Denial Of Service attacks)
2724 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))
2728 const char *protocolname;
2731 SZ_Clear(&net_message);
2732 SZ_Write(&net_message, data, length);
2738 if (developer.integer >= 10)
2739 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2740 if(!islocal && sv_public.integer <= -2)
2743 protocolname = MSG_ReadString();
2744 protocolnumber = MSG_ReadByte();
2745 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2747 if (developer.integer >= 10)
2748 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2749 SZ_Clear(&net_message);
2750 // save space for the header, filled in later
2751 MSG_WriteLong(&net_message, 0);
2752 MSG_WriteByte(&net_message, CCREP_REJECT);
2753 MSG_WriteString(&net_message, "Incompatible version.\n");
2754 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2755 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2756 SZ_Clear(&net_message);
2760 // see if this connect request comes from a known client
2761 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2763 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2765 // this is either a duplicate connection request
2766 // or coming back from a timeout
2767 // (if so, keep their stuff intact)
2770 if (developer.integer >= 10)
2771 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2772 SZ_Clear(&net_message);
2773 // save space for the header, filled in later
2774 MSG_WriteLong(&net_message, 0);
2775 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2776 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2777 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2778 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2779 SZ_Clear(&net_message);
2781 // if client is already spawned, re-send the
2782 // serverinfo message as they'll need it to play
2783 if (client->spawned)
2786 SV_SendServerinfo(client);
2793 // this is a new client, check for connection flood
2794 if (NetConn_PreventConnectFlood(peeraddress))
2797 // find a slot for the new client
2798 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2801 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2803 // connect to the client
2804 // everything is allocated, just fill in the details
2805 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2806 if (developer.integer >= 10)
2807 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2808 // send back the info about the server connection
2809 SZ_Clear(&net_message);
2810 // save space for the header, filled in later
2811 MSG_WriteLong(&net_message, 0);
2812 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2813 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2814 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2815 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2816 SZ_Clear(&net_message);
2817 // now set up the client struct
2819 SV_ConnectClient(clientnum, conn);
2821 NetConn_Heartbeat(1);
2826 if (developer.integer >= 10)
2827 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2828 // no room; try to let player know
2829 SZ_Clear(&net_message);
2830 // save space for the header, filled in later
2831 MSG_WriteLong(&net_message, 0);
2832 MSG_WriteByte(&net_message, CCREP_REJECT);
2833 MSG_WriteString(&net_message, "Server is full.\n");
2834 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2835 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2836 SZ_Clear(&net_message);
2838 case CCREQ_SERVER_INFO:
2839 if (developer.integer >= 10)
2840 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2841 if(!islocal && sv_public.integer <= -1)
2843 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2846 char myaddressstring[128];
2847 if (developer.integer >= 10)
2848 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2849 SZ_Clear(&net_message);
2850 // save space for the header, filled in later
2851 MSG_WriteLong(&net_message, 0);
2852 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2853 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2854 MSG_WriteString(&net_message, myaddressstring);
2855 MSG_WriteString(&net_message, hostname.string);
2856 MSG_WriteString(&net_message, sv.name);
2857 // How many clients are there?
2858 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2859 if (svs.clients[i].active)
2861 MSG_WriteByte(&net_message, numclients);
2862 MSG_WriteByte(&net_message, svs.maxclients);
2863 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2864 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2865 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2866 SZ_Clear(&net_message);
2869 case CCREQ_PLAYER_INFO:
2870 if (developer.integer >= 10)
2871 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2872 if(!islocal && sv_public.integer <= -1)
2876 int playerNumber, activeNumber, clientNumber;
2879 playerNumber = MSG_ReadByte();
2881 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2882 if (client->active && ++activeNumber == playerNumber)
2884 if (clientNumber != svs.maxclients)
2886 SZ_Clear(&net_message);
2887 // save space for the header, filled in later
2888 MSG_WriteLong(&net_message, 0);
2889 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2890 MSG_WriteByte(&net_message, playerNumber);
2891 MSG_WriteString(&net_message, client->name);
2892 MSG_WriteLong(&net_message, client->colors);
2893 MSG_WriteLong(&net_message, client->frags);
2894 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2895 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2896 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2897 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2898 SZ_Clear(&net_message);
2902 case CCREQ_RULE_INFO:
2903 if (developer.integer >= 10)
2904 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2905 if(!islocal && sv_public.integer <= -1)
2912 // find the search start location
2913 prevCvarName = MSG_ReadString();
2914 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2916 // send the response
2917 SZ_Clear(&net_message);
2918 // save space for the header, filled in later
2919 MSG_WriteLong(&net_message, 0);
2920 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2923 MSG_WriteString(&net_message, var->name);
2924 MSG_WriteString(&net_message, var->string);
2926 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2927 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2928 SZ_Clear(&net_message);
2934 SZ_Clear(&net_message);
2935 // we may not have liked the packet, but it was a valid control
2936 // packet, so we're done processing this packet now
2941 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2944 SV_ReadClientMessage();
2952 void NetConn_ServerFrame(void)
2955 lhnetaddress_t peeraddress;
2956 for (i = 0;i < sv_numsockets;i++)
2957 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2958 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2959 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2961 // never timeout loopback connections
2962 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2964 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2966 SV_DropClient(false);
2972 void NetConn_SleepMicroseconds(int microseconds)
2974 LHNET_SleepUntilPacket_Microseconds(microseconds);
2977 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2981 lhnetaddress_t masteraddress;
2982 lhnetaddress_t broadcastaddress;
2985 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2988 // 26000 is the default quake server port, servers on other ports will not
2990 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2991 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2995 for (i = 0;i < cl_numsockets;i++)
2999 const char *cmdname, *extraoptions;
3000 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3002 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3004 // search LAN for Quake servers
3005 SZ_Clear(&net_message);
3006 // save space for the header, filled in later
3007 MSG_WriteLong(&net_message, 0);
3008 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
3009 MSG_WriteString(&net_message, "QUAKE");
3010 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
3011 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
3012 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
3013 SZ_Clear(&net_message);
3015 // search LAN for DarkPlaces servers
3016 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getstatus", &broadcastaddress);
3019 // build the getservers message to send to the dpmaster master servers
3020 if (LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == LHNETADDRESSTYPE_INET6)
3022 cmdname = "getserversExt";
3023 extraoptions = " ipv4 ipv6"; // ask for IPv4 and IPv6 servers
3027 cmdname = "getservers";
3030 dpsnprintf(request, sizeof(request), "\377\377\377\377%s %s %u empty full%s", cmdname, gamename, NET_PROTOCOL_VERSION, extraoptions);
3033 for (masternum = 0;sv_masters[masternum].name;masternum++)
3035 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == af)
3038 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
3042 // search favorite servers
3043 for(j = 0; j < nFavorites; ++j)
3045 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3047 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3048 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, request, true );
3055 // only query QuakeWorld servers when the user wants to
3058 for (i = 0;i < cl_numsockets;i++)
3062 int af = LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]));
3064 if(LHNETADDRESS_GetAddressType(&broadcastaddress) == af)
3066 // search LAN for QuakeWorld servers
3067 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
3069 // build the getservers message to send to the qwmaster master servers
3070 // note this has no -1 prefix, and the trailing nul byte is sent
3071 dpsnprintf(request, sizeof(request), "c\n");
3075 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
3077 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
3079 if (m_state != m_slist)
3081 char lookupstring[128];
3082 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
3083 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
3086 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
3090 // search favorite servers
3091 for(j = 0; j < nFavorites; ++j)
3093 if(LHNETADDRESS_GetAddressType(&favorites[j]) == af)
3095 if(LHNETADDRESS_ToString(&favorites[j], request, sizeof(request), true))
3097 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &favorites[j]);
3098 NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, request, true );
3105 if (!masterquerycount)
3107 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
3108 M_Update_Return_Reason("No network");
3112 void NetConn_Heartbeat(int priority)
3114 lhnetaddress_t masteraddress;
3116 lhnetsocket_t *mysocket;
3118 // if it's a state change (client connected), limit next heartbeat to no
3119 // more than 30 sec in the future
3120 if (priority == 1 && nextheartbeattime > realtime + 30.0)
3121 nextheartbeattime = realtime + 30.0;
3123 // limit heartbeatperiod to 30 to 270 second range,
3124 // lower limit is to avoid abusing master servers with excess traffic,
3125 // upper limit is to avoid timing out on the master server (which uses
3127 if (sv_heartbeatperiod.value < 30)
3128 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
3129 if (sv_heartbeatperiod.value > 270)
3130 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
3132 // make advertising optional and don't advertise singleplayer games, and
3133 // only send a heartbeat as often as the admin wants
3134 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
3136 nextheartbeattime = realtime + sv_heartbeatperiod.value;
3137 for (masternum = 0;sv_masters[masternum].name;masternum++)
3138 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
3139 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
3143 static void Net_Heartbeat_f(void)
3146 NetConn_Heartbeat(2);
3148 Con_Print("No server running, can not heartbeat to master server.\n");
3151 void PrintStats(netconn_t *conn)
3153 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
3154 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->outgoing_unreliable_sequence, conn->qw.incoming_sequence);
3156 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
3159 void Net_Stats_f(void)
3162 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
3163 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
3164 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
3165 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
3166 Con_Printf("packetsSent = %i\n", packetsSent);
3167 Con_Printf("packetsReSent = %i\n", packetsReSent);
3168 Con_Printf("packetsReceived = %i\n", packetsReceived);
3169 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
3170 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
3171 Con_Print("connections =\n");
3172 for (conn = netconn_list;conn;conn = conn->next)
3176 void Net_Refresh_f(void)
3178 if (m_state != m_slist) {
3179 Con_Print("Sending new requests to master servers\n");
3180 ServerList_QueryList(false, true, false, true);
3181 Con_Print("Listening for replies...\n");
3183 ServerList_QueryList(false, true, false, false);
3186 void Net_Slist_f(void)
3188 ServerList_ResetMasks();
3189 serverlist_sortbyfield = SLIF_PING;
3190 serverlist_sortflags = 0;
3191 if (m_state != m_slist) {
3192 Con_Print("Sending requests to master servers\n");
3193 ServerList_QueryList(true, true, false, true);
3194 Con_Print("Listening for replies...\n");
3196 ServerList_QueryList(true, true, false, false);
3199 void Net_SlistQW_f(void)
3201 ServerList_ResetMasks();
3202 serverlist_sortbyfield = SLIF_PING;
3203 serverlist_sortflags = 0;
3204 if (m_state != m_slist) {
3205 Con_Print("Sending requests to master servers\n");
3206 ServerList_QueryList(true, false, true, true);
3207 serverlist_consoleoutput = true;
3208 Con_Print("Listening for replies...\n");
3210 ServerList_QueryList(true, false, true, false);
3213 void NetConn_Init(void)
3216 lhnetaddress_t tempaddress;
3217 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
3218 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
3219 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
3220 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
3221 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
3222 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
3223 Cvar_RegisterVariable(&rcon_restricted_password);
3224 Cvar_RegisterVariable(&rcon_restricted_commands);
3225 Cvar_RegisterVariable(&rcon_secure_maxdiff);
3226 Cvar_RegisterVariable(&net_slist_queriespersecond);
3227 Cvar_RegisterVariable(&net_slist_queriesperframe);
3228 Cvar_RegisterVariable(&net_slist_timeout);
3229 Cvar_RegisterVariable(&net_slist_maxtries);
3230 Cvar_RegisterVariable(&net_slist_favorites);
3231 Cvar_RegisterVariable(&net_slist_pause);
3232 Cvar_RegisterVariable(&net_messagetimeout);
3233 Cvar_RegisterVariable(&net_connecttimeout);
3234 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
3235 Cvar_RegisterVariable(&cl_netlocalping);
3236 Cvar_RegisterVariable(&cl_netpacketloss_send);
3237 Cvar_RegisterVariable(&cl_netpacketloss_receive);
3238 Cvar_RegisterVariable(&hostname);
3239 Cvar_RegisterVariable(&developer_networking);
3240 Cvar_RegisterVariable(&cl_netport);
3241 Cvar_RegisterVariable(&sv_netport);
3242 Cvar_RegisterVariable(&net_address);
3243 Cvar_RegisterVariable(&net_address_ipv6);
3244 Cvar_RegisterVariable(&sv_public);
3245 Cvar_RegisterVariable(&sv_heartbeatperiod);
3246 for (i = 0;sv_masters[i].name;i++)
3247 Cvar_RegisterVariable(&sv_masters[i]);
3248 Cvar_RegisterVariable(&gameversion);
3249 Cvar_RegisterVariable(&gameversion_min);
3250 Cvar_RegisterVariable(&gameversion_max);
3251 // 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.
3252 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
3254 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
3256 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
3257 Cvar_SetQuick(&net_address, com_argv[i + 1]);
3260 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
3262 // 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
3263 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
3265 i = atoi(com_argv[i + 1]);
3266 if (i >= 0 && i < 65536)
3268 Con_Printf("-port option used, setting port cvar to %i\n", i);
3269 Cvar_SetValueQuick(&sv_netport, i);
3272 Con_Printf("-port option used, but %i is not a valid port number\n", i);
3276 net_message.data = net_message_buf;
3277 net_message.maxsize = sizeof(net_message_buf);
3278 net_message.cursize = 0;
3282 void NetConn_Shutdown(void)
3284 NetConn_CloseClientPorts();
3285 NetConn_CloseServerPorts();