2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2002 Mathieu Olivier
4 Copyright (C) 2003 Forest Hale
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 #define QWMASTER_PORT 27000
27 #define DPMASTER_PORT 27950
29 // note this defaults on for dedicated servers, off for listen servers
30 cvar_t sv_public = {0, "sv_public", "0", "1: advertises this server on the master server (so that players can find it in the server browser); 0: allow direct queries only; -1: do not respond to direct queries; -2: do not allow anyone to connect"};
31 static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"};
33 static cvar_t sv_masters [] =
35 {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"},
36 {CVAR_SAVE, "sv_master2", "", "user-chosen master server 2"},
37 {CVAR_SAVE, "sv_master3", "", "user-chosen master server 3"},
38 {CVAR_SAVE, "sv_master4", "", "user-chosen master server 4"},
39 {0, "sv_masterextra1", "ghdigital.com", "default master server 1 (admin: LordHavoc)"}, // admin: LordHavoc
40 {0, "sv_masterextra2", "dpmaster.deathmask.net", "default master server 2 (admin: Willis)"}, // admin: Willis
41 {0, "sv_masterextra3", "excalibur.nvg.ntnu.no", "default master server 3 (admin: tChr)"}, // admin: tChr
45 static cvar_t sv_qwmasters [] =
47 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
48 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
49 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
50 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
51 {0, "sv_qwmasterextra1", "192.246.40.37:27000", "id Limbo (admin: id Software)"},
52 {0, "sv_qwmasterextra2", "192.246.40.37:27002", "id CTF (admin: id Software)"},
53 {0, "sv_qwmasterextra3", "192.246.40.37:27003", "id TeamFortress (admin: id Software)"},
54 {0, "sv_qwmasterextra4", "192.246.40.37:27004", "id Miscilaneous (admin: id Software)"},
55 {0, "sv_qwmasterextra5", "192.246.40.37:27006", "id Deathmatch Only (admin: id Software)"},
56 {0, "sv_qwmasterextra6", "150.254.66.120:27000", "Poland's master server. (admin: unknown)"},
57 {0, "sv_qwmasterextra7", "62.112.145.129:27000", "Ocrana master server. (admin: unknown)"},
58 {0, "sv_qwmasterextra8", "master.edome.net", "edome master server. (admin: unknown)"},
59 {0, "sv_qwmasterextra9", "qwmaster.barrysworld.com", "barrysworld master server. (admin: unknown)"},
60 {0, "sv_qwmasterextra10", "qwmaster.ocrana.de:27000", "Ocrana2 master server. (admin: unknown)"},
61 {0, "sv_qwmasterextra11", "213.221.174.165:27000", "unknown1 master server. (admin: unknown)"},
62 {0, "sv_qwmasterextra12", "195.74.0.8", "unknown2 master server. (admin: unknown)"},
63 {0, "sv_qwmasterextra13", "204.182.161.2", "unknown3 master server. (admin: unknown)"},
67 static double nextheartbeattime = 0;
69 sizebuf_t net_message;
70 static unsigned char net_message_buf[NET_MAXMESSAGE];
72 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
73 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
74 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)"};
75 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
76 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
78 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)"};
79 static cvar_t cl_netpacketloss = {0, "cl_netpacketloss","0", "drops this percentage of packets (incoming and outgoing), useful for testing network protocol robustness (effects failing to start, sounds failing to play, etc)"};
80 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
81 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)"};
82 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
83 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)"};
85 static cvar_t gameversion = {0, "gameversion", "0", "version of game data (mod-specific), when client and server gameversion mismatch in the server browser the server is shown as incompatible"};
87 /* statistic counters */
88 static int packetsSent = 0;
89 static int packetsReSent = 0;
90 static int packetsReceived = 0;
91 static int receivedDuplicateCount = 0;
92 static int droppedDatagrams = 0;
94 static int unreliableMessagesSent = 0;
95 static int unreliableMessagesReceived = 0;
96 static int reliableMessagesSent = 0;
97 static int reliableMessagesReceived = 0;
99 double masterquerytime = -1000;
100 int masterquerycount = 0;
101 int masterreplycount = 0;
102 int serverquerycount = 0;
103 int serverreplycount = 0;
105 // this is only false if there are still servers left to query
106 static qboolean serverlist_querysleep = true;
107 // this is pushed a second or two ahead of realtime whenever a master server
108 // reply is received, to avoid issuing queries while master replies are still
109 // flooding in (which would make a mess of the ping times)
110 static double serverlist_querywaittime = 0;
112 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
113 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
115 static int cl_numsockets;
116 static lhnetsocket_t *cl_sockets[16];
117 static int sv_numsockets;
118 static lhnetsocket_t *sv_sockets[16];
120 netconn_t *netconn_list = NULL;
121 mempool_t *netconn_mempool = NULL;
123 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
124 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
125 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
126 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
128 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
129 int net_extresponse_count = 0;
130 int net_extresponse_last = 0;
132 // ServerList interface
133 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
134 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
136 serverlist_infofield_t serverlist_sortbyfield;
137 qboolean serverlist_sortdescending;
139 int serverlist_viewcount = 0;
140 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
142 int serverlist_cachecount;
143 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
145 qboolean serverlist_consoleoutput;
147 // helper function to insert a value into the viewset
148 // spare entries will be removed
149 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
152 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
153 i = serverlist_viewcount++;
155 i = SERVERLIST_VIEWLISTSIZE - 1;
158 for( ; i > index ; i-- )
159 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
161 serverlist_viewlist[index] = entry;
164 // we suppose serverlist_viewcount to be valid, ie > 0
165 static void _ServerList_ViewList_Helper_Remove( int index )
167 serverlist_viewcount--;
168 for( ; index < serverlist_viewcount ; index++ )
169 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
172 // returns true if A should be inserted before B
173 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
175 int result = 0; // > 0 if for numbers A > B and for text if A < B
177 switch( serverlist_sortbyfield ) {
179 result = A->info.ping - B->info.ping;
181 case SLIF_MAXPLAYERS:
182 result = A->info.maxplayers - B->info.maxplayers;
184 case SLIF_NUMPLAYERS:
185 result = A->info.numplayers - B->info.numplayers;
188 result = A->info.numbots - B->info.numbots;
191 result = A->info.numhumans - B->info.numhumans;
194 result = A->info.protocol - B->info.protocol;
197 result = strcmp( B->info.cname, A->info.cname );
200 result = strcmp( B->info.game, A->info.game );
203 result = strcmp( B->info.map, A->info.map );
206 result = strcmp( B->info.mod, A->info.mod );
209 result = strcmp( B->info.name, A->info.name );
212 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
216 if( serverlist_sortdescending )
220 // if the chosen sort key is identical, sort by index
221 // (makes this a stable sort, so that later replies from servers won't
222 // shuffle the servers around when they have the same ping)
226 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
228 // This should actually be done with some intermediate and end-of-function return
240 case SLMO_GREATEREQUAL:
242 case SLMO_NOTCONTAIN:
245 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
250 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
253 char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
254 for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
255 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
257 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
258 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
261 // Same here, also using an intermediate & final return would be more appropriate
265 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
266 case SLMO_NOTCONTAIN:
267 return !*bufferB || !strstr( bufferA, bufferB );
269 return strcmp( bufferA, bufferB ) < 0;
271 return strcmp( bufferA, bufferB ) <= 0;
273 return strcmp( bufferA, bufferB ) == 0;
275 return strcmp( bufferA, bufferB ) > 0;
277 return strcmp( bufferA, bufferB ) != 0;
278 case SLMO_GREATEREQUAL:
279 return strcmp( bufferA, bufferB ) >= 0;
281 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
286 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
288 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
290 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
292 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
294 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
296 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
298 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
300 if( *mask->info.cname
301 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
304 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
307 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
310 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
313 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
318 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
322 // reject incompatible servers
323 if (entry->info.gameversion != gameversion.integer)
326 // FIXME: change this to be more readable (...)
327 // now check whether it passes through the masks
328 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
329 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
332 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
333 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
335 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
338 if( !serverlist_viewcount ) {
339 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
342 // ok, insert it, we just need to find out where exactly:
345 // check whether to insert it as new first item
346 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
347 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
349 } // check whether to insert it as new last item
350 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
351 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
355 end = serverlist_viewcount - 1;
356 while( end > start + 1 )
358 mid = (start + end) / 2;
359 // test the item that lies in the middle between start and end
360 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
361 // the item has to be in the upper half
364 // the item has to be in the lower half
367 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
370 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
373 for( i = 0; i < serverlist_viewcount; i++ )
375 if (serverlist_viewlist[i] == entry)
377 _ServerList_ViewList_Helper_Remove(i);
383 void ServerList_RebuildViewList(void)
387 serverlist_viewcount = 0;
388 for( i = 0 ; i < serverlist_cachecount ; i++ )
389 if( serverlist_cache[i].query == SQS_QUERIED )
390 ServerList_ViewList_Insert( &serverlist_cache[i] );
393 void ServerList_ResetMasks(void)
395 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
396 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
400 static void _ServerList_Test(void)
403 for( i = 0 ; i < 1024 ; i++ ) {
404 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
405 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
406 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
407 serverlist_cache[serverlist_cachecount].finished = true;
408 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
409 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
410 serverlist_cachecount++;
415 void ServerList_QueryList(qboolean querydp, qboolean queryqw)
417 masterquerytime = realtime;
418 masterquerycount = 0;
419 masterreplycount = 0;
420 serverquerycount = 0;
421 serverreplycount = 0;
422 serverlist_cachecount = 0;
423 serverlist_viewcount = 0;
424 serverlist_consoleoutput = false;
426 //_ServerList_Test();
428 NetConn_QueryMasters(querydp, queryqw);
433 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
435 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
439 if (cl_netpacketloss.integer)
440 for (i = 0;i < cl_numsockets;i++)
441 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
443 if (developer_networking.integer)
445 char addressstring[128], addressstring2[128];
446 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
449 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
450 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
451 Com_HexDumpToConsole((unsigned char *)data, length);
454 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
459 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
463 if (cl_netpacketloss.integer)
464 for (i = 0;i < cl_numsockets;i++)
465 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
467 ret = LHNET_Write(mysocket, data, length, peeraddress);
468 if (developer_networking.integer)
470 char addressstring[128], addressstring2[128];
471 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
472 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
473 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
474 Com_HexDumpToConsole((unsigned char *)data, length);
479 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
481 // note this does not include the trailing NULL because we add that in the parser
482 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
485 qboolean NetConn_CanSend(netconn_t *conn)
487 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
488 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
489 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
490 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
491 if (realtime > conn->cleartime)
495 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
500 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate)
504 // if this packet was supposedly choked, but we find ourselves sending one
505 // anyway, make sure the size counting starts at zero
506 // (this mostly happens on level changes and disconnects and such)
507 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
508 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
510 if (protocol == PROTOCOL_QUAKEWORLD)
513 qboolean sendreliable;
515 // note that it is ok to send empty messages to the qw server,
516 // otherwise it won't respond to us at all
518 sendreliable = false;
519 // if the remote side dropped the last reliable message, resend it
520 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
522 // if the reliable transmit buffer is empty, copy the current message out
523 if (!conn->sendMessageLength && conn->message.cursize)
525 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
526 conn->sendMessageLength = conn->message.cursize;
527 SZ_Clear(&conn->message); // clear the message buffer
528 conn->qw.reliable_sequence ^= 1;
531 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
532 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->qw.outgoing_sequence | ((unsigned int)sendreliable<<31));
533 // last received unreliable packet number, and last received reliable packet number (0 or 1)
534 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
536 conn->qw.outgoing_sequence++;
537 // client sends qport in every packet
538 if (conn == cls.netcon)
540 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
542 // also update cls.qw_outgoing_sequence
543 cls.qw_outgoing_sequence = conn->qw.outgoing_sequence;
545 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
547 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
551 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
553 // add the reliable message if there is one
556 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
557 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
558 packetLen += conn->sendMessageLength;
559 conn->qw.last_reliable_sequence = conn->qw.outgoing_sequence;
562 // add the unreliable message if possible
563 if (packetLen + data->cursize <= 1400)
565 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
566 memcpy(sendbuffer + packetLen, data->data, data->cursize);
567 packetLen += data->cursize;
570 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
573 unreliableMessagesSent++;
575 totallen += packetLen + 18;
579 unsigned int packetLen;
580 unsigned int dataLen;
582 unsigned int *header;
584 // if a reliable message fragment has been lost, send it again
585 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
587 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
589 dataLen = conn->sendMessageLength;
594 dataLen = MAX_PACKETFRAGMENT;
598 packetLen = NET_HEADERSIZE + dataLen;
600 header = (unsigned int *)sendbuffer;
601 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
602 header[1] = BigLong(conn->nq.sendSequence - 1);
603 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
605 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
607 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
609 conn->lastSendTime = realtime;
613 totallen += packetLen + 18;
616 // if we have a new reliable message to send, do so
617 if (!conn->sendMessageLength && conn->message.cursize)
619 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
621 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
622 conn->message.overflowed = true;
626 if (developer_networking.integer && conn == cls.netcon)
628 Con_Print("client sending reliable message to server:\n");
629 SZ_HexDumpToConsole(&conn->message);
632 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
633 conn->sendMessageLength = conn->message.cursize;
634 SZ_Clear(&conn->message);
636 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
638 dataLen = conn->sendMessageLength;
643 dataLen = MAX_PACKETFRAGMENT;
647 packetLen = NET_HEADERSIZE + dataLen;
649 header = (unsigned int *)sendbuffer;
650 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
651 header[1] = BigLong(conn->nq.sendSequence);
652 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
654 conn->nq.sendSequence++;
656 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
658 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
660 conn->lastSendTime = realtime;
662 reliableMessagesSent++;
664 totallen += packetLen + 18;
667 // if we have an unreliable message to send, do so
670 packetLen = NET_HEADERSIZE + data->cursize;
672 if (packetLen > (int)sizeof(sendbuffer))
674 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
678 header = (unsigned int *)sendbuffer;
679 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
680 header[1] = BigLong(conn->nq.unreliableSendSequence);
681 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
683 conn->nq.unreliableSendSequence++;
685 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
687 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
690 unreliableMessagesSent++;
693 totallen += packetLen + 18;
697 // delay later packets to obey rate limit
698 if (conn->cleartime < realtime - 0.1)
699 conn->cleartime = realtime - 0.1;
700 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
701 if (conn->cleartime < realtime)
702 conn->cleartime = realtime;
707 void NetConn_CloseClientPorts(void)
709 for (;cl_numsockets > 0;cl_numsockets--)
710 if (cl_sockets[cl_numsockets - 1])
711 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
714 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
716 lhnetaddress_t address;
718 char addressstring2[1024];
719 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
721 if ((s = LHNET_OpenSocket_Connectionless(&address)))
723 cl_sockets[cl_numsockets++] = s;
724 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
725 Con_Printf("Client opened a socket on address %s\n", addressstring2);
729 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
730 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
734 Con_Printf("Client unable to parse address %s\n", addressstring);
737 void NetConn_OpenClientPorts(void)
740 NetConn_CloseClientPorts();
741 port = bound(0, cl_netport.integer, 65535);
742 if (cl_netport.integer != port)
743 Cvar_SetValueQuick(&cl_netport, port);
744 Con_Printf("Client using port %i\n", port);
745 NetConn_OpenClientPort("local:2", 0);
746 NetConn_OpenClientPort(net_address.string, port);
747 //NetConn_OpenClientPort(net_address_ipv6.string, port);
750 void NetConn_CloseServerPorts(void)
752 for (;sv_numsockets > 0;sv_numsockets--)
753 if (sv_sockets[sv_numsockets - 1])
754 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
757 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
759 lhnetaddress_t address;
762 char addressstring2[1024];
764 for (port = defaultport; port <= defaultport + 100; port++)
766 if (LHNETADDRESS_FromString(&address, addressstring, port))
768 if ((s = LHNET_OpenSocket_Connectionless(&address)))
770 sv_sockets[sv_numsockets++] = s;
771 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
772 Con_Printf("Server listening on address %s\n", addressstring2);
777 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
778 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
783 Con_Printf("Server unable to parse address %s\n", addressstring);
784 // if it cant parse one address, it wont be able to parse another for sure
790 void NetConn_OpenServerPorts(int opennetports)
793 NetConn_CloseServerPorts();
794 NetConn_UpdateSockets();
795 port = bound(0, sv_netport.integer, 65535);
798 Con_Printf("Server using port %i\n", port);
799 if (sv_netport.integer != port)
800 Cvar_SetValueQuick(&sv_netport, port);
801 if (cls.state != ca_dedicated)
802 NetConn_OpenServerPort("local:1", 0);
805 NetConn_OpenServerPort(net_address.string, port);
806 //NetConn_OpenServerPort(net_address_ipv6.string, port);
808 if (sv_numsockets == 0)
809 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
812 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
814 int i, a = LHNETADDRESS_GetAddressType(address);
815 for (i = 0;i < cl_numsockets;i++)
816 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
817 return cl_sockets[i];
821 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
823 int i, a = LHNETADDRESS_GetAddressType(address);
824 for (i = 0;i < sv_numsockets;i++)
825 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
826 return sv_sockets[i];
830 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
833 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
834 conn->mysocket = mysocket;
835 conn->peeraddress = *peeraddress;
836 conn->lastMessageTime = realtime;
837 conn->message.data = conn->messagedata;
838 conn->message.maxsize = sizeof(conn->messagedata);
839 conn->message.cursize = 0;
840 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
841 // reduce effectiveness of connection request floods
842 conn->timeout = realtime + net_connecttimeout.value;
843 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
844 conn->next = netconn_list;
849 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
850 void NetConn_Close(netconn_t *conn)
853 // remove connection from list
855 // allow the client to reconnect immediately
856 NetConn_ClearConnectFlood(&(conn->peeraddress));
858 if (conn == netconn_list)
859 netconn_list = conn->next;
862 for (c = netconn_list;c;c = c->next)
866 c->next = conn->next;
870 // not found in list, we'll avoid crashing here...
878 static int clientport = -1;
879 static int clientport2 = -1;
880 static int hostport = -1;
881 void NetConn_UpdateSockets(void)
883 if (cls.state != ca_dedicated)
885 if (clientport2 != cl_netport.integer)
887 clientport2 = cl_netport.integer;
888 if (cls.state == ca_connected)
889 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
891 if (cls.state == ca_disconnected && clientport != clientport2)
893 clientport = clientport2;
894 NetConn_CloseClientPorts();
896 if (cl_numsockets == 0)
897 NetConn_OpenClientPorts();
900 if (hostport != sv_netport.integer)
902 hostport = sv_netport.integer;
904 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
908 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
910 int originallength = length;
914 // TODO: add netgraph stuff rather than just packetloss counting...
916 if (protocol == PROTOCOL_QUAKEWORLD)
918 int sequence, sequence_ack;
919 int reliable_ack, reliable_message;
923 sequence = LittleLong(*((int *)(data + 0)));
924 sequence_ack = LittleLong(*((int *)(data + 4)));
928 if (conn != cls.netcon)
933 // 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?)
934 qport = LittleShort(*((int *)(data + 8)));
940 reliable_message = (sequence >> 31) & 1;
941 reliable_ack = (sequence_ack >> 31) & 1;
942 sequence &= ~(1<<31);
943 sequence_ack &= ~(1<<31);
944 if (sequence <= conn->qw.incoming_sequence)
946 //Con_DPrint("Got a stale datagram\n");
949 count = sequence - (conn->qw.incoming_sequence + 1);
952 droppedDatagrams += count;
953 //Con_DPrintf("Dropped %u datagram(s)\n", count);
956 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
957 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
958 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
959 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
962 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
963 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
964 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
965 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
966 if (reliable_ack == conn->qw.reliable_sequence)
968 // received, now we will be able to send another reliable message
969 conn->sendMessageLength = 0;
970 reliableMessagesReceived++;
972 conn->qw.incoming_sequence = sequence;
973 if (conn == cls.netcon)
974 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
975 conn->qw.incoming_acknowledged = sequence_ack;
976 conn->qw.incoming_reliable_acknowledged = reliable_ack;
977 if (reliable_message)
978 conn->qw.incoming_reliable_sequence ^= 1;
979 conn->lastMessageTime = realtime;
980 conn->timeout = realtime + newtimeout;
981 unreliableMessagesReceived++;
982 SZ_Clear(&net_message);
983 SZ_Write(&net_message, data, length);
991 unsigned int sequence;
994 qlength = (unsigned int)BigLong(((int *)data)[0]);
995 flags = qlength & ~NETFLAG_LENGTH_MASK;
996 qlength &= NETFLAG_LENGTH_MASK;
997 // control packets were already handled
998 if (!(flags & NETFLAG_CTL) && qlength == length)
1000 sequence = BigLong(((int *)data)[1]);
1004 if (flags & NETFLAG_UNRELIABLE)
1006 if (sequence >= conn->nq.unreliableReceiveSequence)
1008 if (sequence > conn->nq.unreliableReceiveSequence)
1010 count = sequence - conn->nq.unreliableReceiveSequence;
1011 droppedDatagrams += count;
1012 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1015 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1016 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1017 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1018 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1021 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1022 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1023 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1024 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1025 conn->nq.unreliableReceiveSequence = sequence + 1;
1026 conn->lastMessageTime = realtime;
1027 conn->timeout = realtime + newtimeout;
1028 unreliableMessagesReceived++;
1031 SZ_Clear(&net_message);
1032 SZ_Write(&net_message, data, length);
1038 // Con_DPrint("Got a stale datagram\n");
1041 else if (flags & NETFLAG_ACK)
1043 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1044 if (sequence == (conn->nq.sendSequence - 1))
1046 if (sequence == conn->nq.ackSequence)
1048 conn->nq.ackSequence++;
1049 if (conn->nq.ackSequence != conn->nq.sendSequence)
1050 Con_DPrint("ack sequencing error\n");
1051 conn->lastMessageTime = realtime;
1052 conn->timeout = realtime + newtimeout;
1053 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1055 unsigned int packetLen;
1056 unsigned int dataLen;
1058 unsigned int *header;
1060 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1061 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1063 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1065 dataLen = conn->sendMessageLength;
1070 dataLen = MAX_PACKETFRAGMENT;
1074 packetLen = NET_HEADERSIZE + dataLen;
1076 header = (unsigned int *)sendbuffer;
1077 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1078 header[1] = BigLong(conn->nq.sendSequence);
1079 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1081 conn->nq.sendSequence++;
1083 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1085 conn->lastSendTime = realtime;
1090 conn->sendMessageLength = 0;
1093 // Con_DPrint("Duplicate ACK received\n");
1096 // Con_DPrint("Stale ACK received\n");
1099 else if (flags & NETFLAG_DATA)
1101 unsigned int temppacket[2];
1102 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1103 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1104 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1105 temppacket[1] = BigLong(sequence);
1106 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1107 if (sequence == conn->nq.receiveSequence)
1109 conn->lastMessageTime = realtime;
1110 conn->timeout = realtime + newtimeout;
1111 conn->nq.receiveSequence++;
1112 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1113 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1114 conn->receiveMessageLength += length;
1116 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1117 "Dropping the message!\n", sequence );
1118 conn->receiveMessageLength = 0;
1121 if (flags & NETFLAG_EOM)
1123 reliableMessagesReceived++;
1124 length = conn->receiveMessageLength;
1125 conn->receiveMessageLength = 0;
1128 SZ_Clear(&net_message);
1129 SZ_Write(&net_message, conn->receiveMessage, length);
1136 receivedDuplicateCount++;
1144 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1146 cls.connect_trying = false;
1147 M_Update_Return_Reason("");
1148 // the connection request succeeded, stop current connection and set up a new connection
1150 // if we're connecting to a remote server, shut down any local server
1151 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1152 Host_ShutdownServer ();
1153 // allocate a net connection to keep track of things
1154 cls.netcon = NetConn_Open(mysocket, peeraddress);
1155 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1156 key_dest = key_game;
1158 cls.demonum = -1; // not in the demo loop now
1159 cls.state = ca_connected;
1160 cls.signon = 0; // need all the signon messages before playing
1161 cls.protocol = initialprotocol;
1162 // reset move sequence numbering on this new connection
1163 cls.movesequence = 0;
1164 cls.servermovesequence = 0;
1165 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1166 Cmd_ForwardStringToServer("new");
1167 if (cls.protocol == PROTOCOL_QUAKE)
1169 // write a keepalive (clc_nop) as it seems to greatly improve the
1170 // chances of connecting to a netquake server
1172 unsigned char buf[4];
1173 memset(&msg, 0, sizeof(msg));
1175 msg.maxsize = sizeof(buf);
1176 MSG_WriteChar(&msg, clc_nop);
1177 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000);
1181 int NetConn_IsLocalGame(void)
1183 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1188 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1192 // search the cache for this server and update it
1193 for (n = 0;n < serverlist_cachecount;n++)
1194 if (!strcmp(addressstring, serverlist_cache[n].info.cname))
1196 if (n == serverlist_cachecount)
1198 // LAN search doesnt require an answer from the master server so we wont
1199 // know the ping nor will it be initialized already...
1202 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1205 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1206 // store the data the engine cares about (address and ping)
1207 strlcpy(serverlist_cache[serverlist_cachecount].info.cname, addressstring, sizeof(serverlist_cache[serverlist_cachecount].info.cname));
1208 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1209 serverlist_cache[serverlist_cachecount].querytime = realtime;
1210 // if not in the slist menu we should print the server to console
1211 if (serverlist_consoleoutput)
1212 Con_Printf("querying %s\n", addressstring);
1213 ++serverlist_cachecount;
1215 // if this is the first reply from this server, count it as having replied
1216 if (serverlist_cache[n].info.ping == 100000)
1218 pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0 + 0.5);
1219 pingtime = bound(0, pingtime, 9999);
1221 serverlist_cache[n].info.ping = min(serverlist_cache[n].info.ping, pingtime);
1222 // other server info is updated by the caller
1226 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1228 serverlist_info_t *info = &serverlist_cache[n].info;
1229 // update description strings for engine menu and console output
1230 dpsnprintf(serverlist_cache[n].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);
1231 dpsnprintf(serverlist_cache[n].line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
1232 if (serverlist_cache[n].query == SQS_QUERIED)
1233 ServerList_ViewList_Remove(&serverlist_cache[n]);
1234 // if not in the slist menu we should print the server to console (if wanted)
1235 else if( serverlist_consoleoutput )
1236 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1237 // and finally, update the view set
1238 ServerList_ViewList_Insert( &serverlist_cache[n] );
1239 serverlist_cache[n].query = SQS_QUERIED;
1242 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1244 qboolean fromserver;
1245 int ret, c, control;
1247 char *string, addressstring2[128], ipstring[32];
1248 char stringbuf[16384];
1250 // quakeworld ingame packet
1251 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1253 // convert the address to a string incase we need it
1254 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1256 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1258 // received a command string - strip off the packaging and put it
1259 // into our string buffer with NULL termination
1262 length = min(length, (int)sizeof(stringbuf) - 1);
1263 memcpy(stringbuf, data, length);
1264 stringbuf[length] = 0;
1267 if (developer_networking.integer)
1269 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1270 Com_HexDumpToConsole(data, length);
1273 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1275 // darkplaces or quake3
1276 char protocolnames[1400];
1277 Protocol_Names(protocolnames, sizeof(protocolnames));
1278 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1279 M_Update_Return_Reason("Got challenge response");
1280 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1281 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1282 // TODO: add userinfo stuff here instead of using NQ commands?
1283 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1286 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1288 // darkplaces or quake3
1289 M_Update_Return_Reason("Accepted");
1290 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1293 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1295 char rejectreason[32];
1296 cls.connect_trying = false;
1298 length = max(length - 7, (int)sizeof(rejectreason) - 1);
1299 memcpy(rejectreason, string, length);
1300 rejectreason[length] = 0;
1301 M_Update_Return_Reason(rejectreason);
1304 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1306 serverlist_info_t *info;
1310 // search the cache for this server and update it
1311 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1315 info = &serverlist_cache[n].info;
1320 info->protocol = -1;
1321 info->numplayers = 0;
1323 info->maxplayers = 0;
1324 info->gameversion = 0;
1325 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1326 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1327 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1328 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1329 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1330 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1331 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1332 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1333 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1334 info->numhumans = info->numplayers - info->numbots;
1336 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1340 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1342 // Extract the IP addresses
1346 if (serverlist_consoleoutput)
1347 Con_Print("received DarkPlaces server list...\n");
1348 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1352 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1353 if (serverlist_consoleoutput && developer_networking.integer)
1354 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1355 // ignore the rest of the message if the serverlist is full
1356 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1358 // also ignore it if we have already queried it (other master server response)
1359 for( n = 0 ; n < serverlist_cachecount ; n++ )
1360 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1362 if( n >= serverlist_cachecount )
1366 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1367 serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_DARKPLACES7;
1368 // store the data the engine cares about (address and ping)
1369 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1370 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1371 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1373 ++serverlist_cachecount;
1376 // move on to next address in packet
1380 // begin or resume serverlist queries
1381 serverlist_querysleep = false;
1382 serverlist_querywaittime = realtime + 3;
1385 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1387 // Extract the IP addresses
1391 if (serverlist_consoleoutput)
1392 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1393 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1397 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1398 if (serverlist_consoleoutput && developer_networking.integer)
1399 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1400 // ignore the rest of the message if the serverlist is full
1401 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1403 // also ignore it if we have already queried it (other master server response)
1404 for( n = 0 ; n < serverlist_cachecount ; n++ )
1405 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1407 if( n >= serverlist_cachecount )
1411 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1412 serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_QUAKEWORLD;
1413 // store the data the engine cares about (address and ping)
1414 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1415 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1416 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1418 ++serverlist_cachecount;
1421 // move on to next address in packet
1425 // begin or resume serverlist queries
1426 serverlist_querysleep = false;
1427 serverlist_querywaittime = realtime + 3;
1430 if (!strncmp(string, "extResponse ", 12))
1432 ++net_extresponse_count;
1433 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1434 net_extresponse_count = NET_EXTRESPONSE_MAX;
1435 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1436 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1439 if (!strncmp(string, "ping", 4))
1441 if (developer.integer >= 10)
1442 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1443 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1446 if (!strncmp(string, "ack", 3))
1448 // QuakeWorld compatibility
1449 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1451 // challenge message
1452 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1453 M_Update_Return_Reason("Got QuakeWorld challenge response");
1454 cls.qw_qport = qport.integer;
1455 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1456 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1457 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1460 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1463 M_Update_Return_Reason("QuakeWorld Accepted");
1464 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1467 if (length > 2 && !memcmp(string, "n\\", 2))
1469 serverlist_info_t *info;
1473 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1474 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1477 // search the cache for this server and update it
1478 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1482 info = &serverlist_cache[n].info;
1483 strlcpy(info->game, "QuakeWorld", sizeof(info->game));;
1484 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1485 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1486 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1488 info->numplayers = 0; // updated below
1489 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1490 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1492 // count active players on server
1493 // (we could gather more info, but we're just after the number)
1494 s = strchr(string, '\n');
1498 while (s < string + length)
1500 for (;s < string + length && *s != '\n';s++)
1502 if (s >= string + length)
1509 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1513 if (string[0] == 'n')
1516 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1518 // we may not have liked the packet, but it was a command packet, so
1519 // we're done processing this packet now
1522 // quakeworld ingame packet
1523 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1526 CL_ParseServerMessage();
1529 // netquake control packets, supported for compatibility only
1530 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1533 serverlist_info_t *info;
1537 SZ_Clear(&net_message);
1538 SZ_Write(&net_message, data, length);
1544 if (developer.integer >= 10)
1545 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1546 if (cls.connect_trying)
1548 lhnetaddress_t clientportaddress;
1549 clientportaddress = *peeraddress;
1550 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1551 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1552 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1553 M_Update_Return_Reason("Accepted");
1554 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1558 if (developer.integer >= 10)
1559 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1560 cls.connect_trying = false;
1561 M_Update_Return_Reason((char *)MSG_ReadString());
1563 case CCREP_SERVER_INFO:
1564 if (developer.integer >= 10)
1565 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1566 // LordHavoc: because the quake server may report weird addresses
1567 // we just ignore it and keep the real address
1569 // search the cache for this server and update it
1570 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1574 info = &serverlist_cache[n].info;
1575 strlcpy(info->game, "Quake", sizeof(info->game));
1576 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1577 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1578 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1579 info->numplayers = MSG_ReadByte();
1580 info->maxplayers = MSG_ReadByte();
1581 info->protocol = MSG_ReadByte();
1583 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1586 case CCREP_PLAYER_INFO:
1587 // we got a CCREP_PLAYER_INFO??
1588 //if (developer.integer >= 10)
1589 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1591 case CCREP_RULE_INFO:
1592 // we got a CCREP_RULE_INFO??
1593 //if (developer.integer >= 10)
1594 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1599 SZ_Clear(&net_message);
1600 // we may not have liked the packet, but it was a valid control
1601 // packet, so we're done processing this packet now
1605 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1606 CL_ParseServerMessage();
1610 void NetConn_QueryQueueFrame(void)
1616 static double querycounter = 0;
1618 if (serverlist_querysleep)
1621 // apply a cool down time after master server replies,
1622 // to avoid messing up the ping times on the servers
1623 if (serverlist_querywaittime > realtime)
1626 // each time querycounter reaches 1.0 issue a query
1627 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1628 maxqueries = (int)querycounter;
1629 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1630 querycounter -= maxqueries;
1632 if( maxqueries == 0 ) {
1636 // scan serverlist and issue queries as needed
1637 serverlist_querysleep = true;
1639 timeouttime = realtime - net_slist_timeout.value;
1640 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1642 serverlist_entry_t *entry = &serverlist_cache[ index ];
1643 if( entry->query != SQS_QUERYING )
1648 serverlist_querysleep = false;
1649 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1654 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1656 lhnetaddress_t address;
1659 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1660 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1662 for (socket = 0; socket < cl_numsockets ; socket++)
1663 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1667 for (socket = 0; socket < cl_numsockets ; socket++)
1668 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1671 entry->querytime = realtime;
1672 entry->querycounter++;
1674 // if not in the slist menu we should print the server to console
1675 if (serverlist_consoleoutput)
1676 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1682 entry->query = SQS_TIMEDOUT;
1687 void NetConn_ClientFrame(void)
1690 lhnetaddress_t peeraddress;
1691 NetConn_UpdateSockets();
1692 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1694 if (cls.connect_remainingtries == 0)
1695 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1696 cls.connect_nextsendtime = realtime + 1;
1697 cls.connect_remainingtries--;
1698 if (cls.connect_remainingtries <= -10)
1700 cls.connect_trying = false;
1701 M_Update_Return_Reason("Connect: Failed");
1704 // try challenge first (newer DP server or QW)
1705 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1706 // then try netquake as a fallback (old server, or netquake)
1707 SZ_Clear(&net_message);
1708 // save space for the header, filled in later
1709 MSG_WriteLong(&net_message, 0);
1710 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1711 MSG_WriteString(&net_message, "QUAKE");
1712 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1713 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1714 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1715 SZ_Clear(&net_message);
1717 for (i = 0;i < cl_numsockets;i++)
1718 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1719 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1720 NetConn_QueryQueueFrame();
1721 if (cls.netcon && realtime > cls.netcon->timeout)
1723 Con_Print("Connection timed out\n");
1725 Host_ShutdownServer ();
1729 #define MAX_CHALLENGES 128
1732 lhnetaddress_t address;
1736 challenge[MAX_CHALLENGES];
1738 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1742 for (i = 0;i < bufferlength - 1;i++)
1746 c = rand () % (127 - 33) + 33;
1747 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1753 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1755 unsigned int nb_clients = 0, nb_bots = 0, i;
1758 // How many clients are there?
1759 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1761 if (svs.clients[i].active)
1764 if (!svs.clients[i].netconnection)
1769 // TODO: we should add more information for the full status string
1770 length = dpsnprintf(out_msg, out_size,
1771 "\377\377\377\377%s\x0A"
1772 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1773 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1776 fullstatus ? "statusResponse" : "infoResponse",
1777 gamename, com_modname, gameversion.integer, svs.maxclients,
1778 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1779 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1780 fullstatus ? "\n" : "");
1782 // Make sure it fits in the buffer
1791 ptr = out_msg + length;
1792 left = (int)out_size - length;
1794 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1796 client_t *cl = &svs.clients[i];
1799 int nameind, cleanind, pingvalue;
1801 char cleanname [sizeof(cl->name)];
1803 // Remove all characters '"' and '\' in the player name
1808 curchar = cl->name[nameind++];
1809 if (curchar != '"' && curchar != '\\')
1811 cleanname[cleanind++] = curchar;
1812 if (cleanind == sizeof(cleanname) - 1)
1815 } while (curchar != '\0');
1817 pingvalue = (int)(cl->ping * 1000.0f);
1818 if(cl->netconnection)
1819 pingvalue = bound(1, pingvalue, 9999);
1822 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1837 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
1839 int floodslotnum, bestfloodslotnum;
1840 double bestfloodtime;
1841 lhnetaddress_t noportpeeraddress;
1842 // see if this is a connect flood
1843 noportpeeraddress = *peeraddress;
1844 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1845 bestfloodslotnum = 0;
1846 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
1847 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1849 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
1851 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
1852 bestfloodslotnum = floodslotnum;
1854 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1856 // this address matches an ongoing flood address
1857 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
1859 // renew the ban on this address so it does not expire
1860 // until the flood has subsided
1861 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
1862 //Con_Printf("Flood detected!\n");
1865 // the flood appears to have subsided, so allow this
1866 bestfloodslotnum = floodslotnum; // reuse the same slot
1870 // begin a new timeout on this address
1871 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
1872 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
1873 //Con_Printf("Flood detection initiated!\n");
1877 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
1880 lhnetaddress_t noportpeeraddress;
1881 // see if this is a connect flood
1882 noportpeeraddress = *peeraddress;
1883 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1884 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1886 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1888 // this address matches an ongoing flood address
1890 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
1891 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
1892 //Con_Printf("Flood cleared!\n");
1897 extern void SV_SendServerinfo (client_t *client);
1898 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1900 int i, ret, clientnum, best;
1903 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1904 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
1909 // convert the address to a string incase we need it
1910 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1912 // see if we can identify the sender as a local player
1913 // (this is necessary for rcon to send a reliable reply if the client is
1914 // actually on the server, not sending remotely)
1915 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1916 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1918 if (i == svs.maxclients)
1921 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1923 // received a command string - strip off the packaging and put it
1924 // into our string buffer with NULL termination
1927 length = min(length, (int)sizeof(stringbuf) - 1);
1928 memcpy(stringbuf, data, length);
1929 stringbuf[length] = 0;
1932 if (developer.integer >= 10)
1934 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1935 Com_HexDumpToConsole(data, length);
1938 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
1940 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1942 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1944 if (besttime > challenge[i].time)
1945 besttime = challenge[best = i].time;
1947 // if we did not find an exact match, choose the oldest and
1948 // update address and string
1949 if (i == MAX_CHALLENGES)
1952 challenge[i].address = *peeraddress;
1953 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1955 challenge[i].time = realtime;
1956 // send the challenge
1957 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1960 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
1965 if (!(s = SearchInfostring(string, "challenge")))
1967 // validate the challenge
1968 for (i = 0;i < MAX_CHALLENGES;i++)
1969 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1971 // if the challenge is not recognized, drop the packet
1972 if (i == MAX_CHALLENGES)
1975 // check engine protocol
1976 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1978 if (developer.integer >= 10)
1979 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1980 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1984 // see if this is a duplicate connection request or a disconnected
1985 // client who is rejoining to the same client slot
1986 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1988 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1990 // this is a known client...
1991 if (client->spawned)
1993 // client crashed and is coming back,
1994 // keep their stuff intact
1995 if (developer.integer >= 10)
1996 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
1997 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1999 SV_SendServerinfo(client);
2004 // client is still trying to connect,
2005 // so we send a duplicate reply
2006 if (developer.integer >= 10)
2007 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2008 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2014 if (NetConn_PreventConnectFlood(peeraddress))
2017 // find an empty client slot for this new client
2018 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2021 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2023 // allocated connection
2024 if (developer.integer >= 10)
2025 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2026 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2027 // now set up the client
2029 SV_ConnectClient(clientnum, conn);
2031 NetConn_Heartbeat(1);
2036 // no empty slots found - server is full
2037 if (developer.integer >= 10)
2038 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2039 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2043 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2045 const char *challenge = NULL;
2047 // If there was a challenge in the getinfo message
2048 if (length > 8 && string[7] == ' ')
2049 challenge = string + 8;
2051 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2053 if (developer.integer >= 10)
2054 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2055 NetConn_WriteString(mysocket, response, peeraddress);
2059 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2061 const char *challenge = NULL;
2063 // If there was a challenge in the getinfo message
2064 if (length > 10 && string[9] == ' ')
2065 challenge = string + 10;
2067 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2069 if (developer.integer >= 10)
2070 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2071 NetConn_WriteString(mysocket, response, peeraddress);
2075 if (length >= 5 && !memcmp(string, "rcon ", 5))
2078 char *s = string + 5;
2080 for (i = 0;*s > ' ';s++)
2081 if (i < (int)sizeof(password) - 1)
2084 if (password[0] > ' ' && !strcmp(rcon_password.string, password))
2086 // looks like a legitimate rcon command with the correct password
2087 Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s);
2088 rcon_redirect = true;
2089 rcon_redirect_bufferpos = 0;
2090 Cmd_ExecuteString(s, src_command);
2091 rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
2092 rcon_redirect = false;
2093 // print resulting text to client
2094 // if client is playing, send a reliable reply instead of
2098 // if the netconnection is loop, then this is the
2099 // local player on a listen mode server, and it would
2100 // result in duplicate printing to the console
2101 // (not that the local player should be using rcon
2102 // when they have the console)
2103 if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2104 SV_ClientPrintf("%s", rcon_redirect_buffer);
2109 dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
2110 NetConn_WriteString(mysocket, response, peeraddress);
2115 if (!strncmp(string, "ping", 4))
2117 if (developer.integer >= 10)
2118 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2119 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2122 if (!strncmp(string, "ack", 3))
2124 // we may not have liked the packet, but it was a command packet, so
2125 // we're done processing this packet now
2128 // netquake control packets, supported for compatibility only, and only
2129 // when running game protocols that are normally served via this connection
2131 // (this protects more modern protocols against being used for
2132 // Quake packet flood Denial Of Service attacks)
2133 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_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3))
2137 const char *protocolname;
2140 SZ_Clear(&net_message);
2141 SZ_Write(&net_message, data, length);
2147 if (developer.integer >= 10)
2148 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2149 if(!islocal && sv_public.integer <= -2)
2152 protocolname = MSG_ReadString();
2153 protocolnumber = MSG_ReadByte();
2154 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2156 if (developer.integer >= 10)
2157 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2158 SZ_Clear(&net_message);
2159 // save space for the header, filled in later
2160 MSG_WriteLong(&net_message, 0);
2161 MSG_WriteByte(&net_message, CCREP_REJECT);
2162 MSG_WriteString(&net_message, "Incompatible version.\n");
2163 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2164 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2165 SZ_Clear(&net_message);
2169 // see if this connect request comes from a known client
2170 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2172 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2174 // this is either a duplicate connection request
2175 // or coming back from a timeout
2176 // (if so, keep their stuff intact)
2179 if (developer.integer >= 10)
2180 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2181 SZ_Clear(&net_message);
2182 // save space for the header, filled in later
2183 MSG_WriteLong(&net_message, 0);
2184 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2185 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2186 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2187 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2188 SZ_Clear(&net_message);
2190 // if client is already spawned, re-send the
2191 // serverinfo message as they'll need it to play
2192 if (client->spawned)
2195 SV_SendServerinfo(client);
2202 // this is a new client, check for connection flood
2203 if (NetConn_PreventConnectFlood(peeraddress))
2206 // find a slot for the new client
2207 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2210 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2212 // connect to the client
2213 // everything is allocated, just fill in the details
2214 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2215 if (developer.integer >= 10)
2216 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2217 // send back the info about the server connection
2218 SZ_Clear(&net_message);
2219 // save space for the header, filled in later
2220 MSG_WriteLong(&net_message, 0);
2221 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2222 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2223 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2224 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2225 SZ_Clear(&net_message);
2226 // now set up the client struct
2228 SV_ConnectClient(clientnum, conn);
2230 NetConn_Heartbeat(1);
2235 if (developer.integer >= 10)
2236 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2237 // no room; try to let player know
2238 SZ_Clear(&net_message);
2239 // save space for the header, filled in later
2240 MSG_WriteLong(&net_message, 0);
2241 MSG_WriteByte(&net_message, CCREP_REJECT);
2242 MSG_WriteString(&net_message, "Server is full.\n");
2243 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2244 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2245 SZ_Clear(&net_message);
2247 case CCREQ_SERVER_INFO:
2248 if (developer.integer >= 10)
2249 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2250 if(!islocal && sv_public.integer <= -1)
2252 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2255 char myaddressstring[128];
2256 if (developer.integer >= 10)
2257 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2258 SZ_Clear(&net_message);
2259 // save space for the header, filled in later
2260 MSG_WriteLong(&net_message, 0);
2261 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2262 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2263 MSG_WriteString(&net_message, myaddressstring);
2264 MSG_WriteString(&net_message, hostname.string);
2265 MSG_WriteString(&net_message, sv.name);
2266 // How many clients are there?
2267 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2268 if (svs.clients[i].active)
2270 MSG_WriteByte(&net_message, numclients);
2271 MSG_WriteByte(&net_message, svs.maxclients);
2272 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2273 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2274 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2275 SZ_Clear(&net_message);
2278 case CCREQ_PLAYER_INFO:
2279 if (developer.integer >= 10)
2280 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2281 if(!islocal && sv_public.integer <= -1)
2285 int playerNumber, activeNumber, clientNumber;
2288 playerNumber = MSG_ReadByte();
2290 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2291 if (client->active && ++activeNumber == playerNumber)
2293 if (clientNumber != svs.maxclients)
2295 SZ_Clear(&net_message);
2296 // save space for the header, filled in later
2297 MSG_WriteLong(&net_message, 0);
2298 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2299 MSG_WriteByte(&net_message, playerNumber);
2300 MSG_WriteString(&net_message, client->name);
2301 MSG_WriteLong(&net_message, client->colors);
2302 MSG_WriteLong(&net_message, client->frags);
2303 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2304 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2305 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2306 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2307 SZ_Clear(&net_message);
2311 case CCREQ_RULE_INFO:
2312 if (developer.integer >= 10)
2313 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2314 if(!islocal && sv_public.integer <= -1)
2321 // find the search start location
2322 prevCvarName = MSG_ReadString();
2323 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2325 // send the response
2326 SZ_Clear(&net_message);
2327 // save space for the header, filled in later
2328 MSG_WriteLong(&net_message, 0);
2329 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2332 MSG_WriteString(&net_message, var->name);
2333 MSG_WriteString(&net_message, var->string);
2335 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2336 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2337 SZ_Clear(&net_message);
2343 SZ_Clear(&net_message);
2344 // we may not have liked the packet, but it was a valid control
2345 // packet, so we're done processing this packet now
2350 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2353 SV_ReadClientMessage();
2361 void NetConn_ServerFrame(void)
2364 lhnetaddress_t peeraddress;
2365 for (i = 0;i < sv_numsockets;i++)
2366 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2367 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2368 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2370 // never timeout loopback connections
2371 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2373 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2375 SV_DropClient(false);
2381 void NetConn_SleepMicroseconds(int microseconds)
2383 LHNET_SleepUntilPacket_Microseconds(microseconds);
2386 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2390 lhnetaddress_t masteraddress;
2391 lhnetaddress_t broadcastaddress;
2394 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2397 // 26000 is the default quake server port, servers on other ports will not
2399 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2400 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2404 for (i = 0;i < cl_numsockets;i++)
2408 // search LAN for Quake servers
2409 SZ_Clear(&net_message);
2410 // save space for the header, filled in later
2411 MSG_WriteLong(&net_message, 0);
2412 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2413 MSG_WriteString(&net_message, "QUAKE");
2414 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2415 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2416 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2417 SZ_Clear(&net_message);
2419 // search LAN for DarkPlaces servers
2420 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2422 // build the getservers message to send to the dpmaster master servers
2423 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2426 for (masternum = 0;sv_masters[masternum].name;masternum++)
2428 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2431 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2438 // only query QuakeWorld servers when the user wants to
2441 for (i = 0;i < cl_numsockets;i++)
2445 // search LAN for QuakeWorld servers
2446 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2448 // build the getservers message to send to the qwmaster master servers
2449 // note this has no -1 prefix, and the trailing nul byte is sent
2450 dpsnprintf(request, sizeof(request), "c\n");
2453 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2455 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2457 if (m_state != m_slist)
2459 char lookupstring[128];
2460 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2461 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2464 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2470 if (!masterquerycount)
2472 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2473 M_Update_Return_Reason("No network");
2477 void NetConn_Heartbeat(int priority)
2479 lhnetaddress_t masteraddress;
2481 lhnetsocket_t *mysocket;
2483 // if it's a state change (client connected), limit next heartbeat to no
2484 // more than 30 sec in the future
2485 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2486 nextheartbeattime = realtime + 30.0;
2488 // limit heartbeatperiod to 30 to 270 second range,
2489 // lower limit is to avoid abusing master servers with excess traffic,
2490 // upper limit is to avoid timing out on the master server (which uses
2492 if (sv_heartbeatperiod.value < 30)
2493 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2494 if (sv_heartbeatperiod.value > 270)
2495 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2497 // make advertising optional and don't advertise singleplayer games, and
2498 // only send a heartbeat as often as the admin wants
2499 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2501 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2502 for (masternum = 0;sv_masters[masternum].name;masternum++)
2503 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2504 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2508 static void Net_Heartbeat_f(void)
2511 NetConn_Heartbeat(2);
2513 Con_Print("No server running, can not heartbeat to master server.\n");
2516 void PrintStats(netconn_t *conn)
2518 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2519 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2521 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2524 void Net_Stats_f(void)
2527 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2528 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2529 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2530 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2531 Con_Printf("packetsSent = %i\n", packetsSent);
2532 Con_Printf("packetsReSent = %i\n", packetsReSent);
2533 Con_Printf("packetsReceived = %i\n", packetsReceived);
2534 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2535 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2536 Con_Print("connections =\n");
2537 for (conn = netconn_list;conn;conn = conn->next)
2541 void Net_Slist_f(void)
2543 ServerList_ResetMasks();
2544 serverlist_sortbyfield = SLIF_PING;
2545 serverlist_sortdescending = false;
2546 if (m_state != m_slist) {
2547 Con_Print("Sending requests to master servers\n");
2548 ServerList_QueryList(true, false);
2549 serverlist_consoleoutput = true;
2550 Con_Print("Listening for replies...\n");
2552 ServerList_QueryList(true, false);
2555 void Net_SlistQW_f(void)
2557 ServerList_ResetMasks();
2558 serverlist_sortbyfield = SLIF_PING;
2559 serverlist_sortdescending = false;
2560 if (m_state != m_slist) {
2561 Con_Print("Sending requests to master servers\n");
2562 ServerList_QueryList(false, true);
2563 serverlist_consoleoutput = true;
2564 Con_Print("Listening for replies...\n");
2566 ServerList_QueryList(false, true);
2569 void NetConn_Init(void)
2572 lhnetaddress_t tempaddress;
2573 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2574 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2575 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2576 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2577 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2578 Cvar_RegisterVariable(&net_slist_queriespersecond);
2579 Cvar_RegisterVariable(&net_slist_queriesperframe);
2580 Cvar_RegisterVariable(&net_slist_timeout);
2581 Cvar_RegisterVariable(&net_slist_maxtries);
2582 Cvar_RegisterVariable(&net_messagetimeout);
2583 Cvar_RegisterVariable(&net_connecttimeout);
2584 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2585 Cvar_RegisterVariable(&cl_netlocalping);
2586 Cvar_RegisterVariable(&cl_netpacketloss);
2587 Cvar_RegisterVariable(&hostname);
2588 Cvar_RegisterVariable(&developer_networking);
2589 Cvar_RegisterVariable(&cl_netport);
2590 Cvar_RegisterVariable(&sv_netport);
2591 Cvar_RegisterVariable(&net_address);
2592 //Cvar_RegisterVariable(&net_address_ipv6);
2593 Cvar_RegisterVariable(&sv_public);
2594 Cvar_RegisterVariable(&sv_heartbeatperiod);
2595 for (i = 0;sv_masters[i].name;i++)
2596 Cvar_RegisterVariable(&sv_masters[i]);
2597 Cvar_RegisterVariable(&gameversion);
2598 // 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.
2599 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2601 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2603 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
2604 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2607 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2609 // 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
2610 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2612 i = atoi(com_argv[i + 1]);
2613 if (i >= 0 && i < 65536)
2615 Con_Printf("-port option used, setting port cvar to %i\n", i);
2616 Cvar_SetValueQuick(&sv_netport, i);
2619 Con_Printf("-port option used, but %i is not a valid port number\n", i);
2623 net_message.data = net_message_buf;
2624 net_message.maxsize = sizeof(net_message_buf);
2625 net_message.cursize = 0;
2629 void NetConn_Shutdown(void)
2631 NetConn_CloseClientPorts();
2632 NetConn_CloseServerPorts();