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", "master.quakeservers.net:27000", "Global master server. (admin: unknown)"},
52 {0, "sv_qwmasterextra2", "asgaard.morphos-team.net:27000", "Global master server. (admin: unknown)"},
53 {0, "sv_qwmasterextra3", "qwmaster.ocrana.de:27000", "German master server. (admin: unknown)"},
54 {0, "sv_qwmasterextra4", "masterserver.exhale.de:27000", "German master server. (admin: unknown)"},
55 {0, "sv_qwmasterextra5", "kubus.rulez.pl:27000", "Poland master server. (admin: unknown)"},
59 static double nextheartbeattime = 0;
61 sizebuf_t net_message;
62 static unsigned char net_message_buf[NET_MAXMESSAGE];
64 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
65 cvar_t net_connecttimeout = {0, "net_connecttimeout","10", "after requesting a connection, the client must reply within this many seconds or be dropped (cuts down on connect floods)"};
66 cvar_t net_connectfloodblockingtimeout = {0, "net_connectfloodblockingtimeout", "5", "when a connection packet is received, it will block all future connect packets from that IP address for this many seconds (cuts down on connect floods)"};
67 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
68 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
70 cvar_t cl_netlocalping = {0, "cl_netlocalping","0", "lags local loopback connection by this much ping time (useful to play more fairly on your own server with people with higher pings)"};
71 static cvar_t cl_netpacketloss_send = {0, "cl_netpacketloss_send","0", "drops this percentage of outgoing packets, useful for testing network protocol robustness (jerky movement, prediction errors, etc)"};
72 static cvar_t cl_netpacketloss_receive = {0, "cl_netpacketloss_receive","0", "drops this percentage of incoming packets, useful for testing network protocol robustness (jerky movement, effects failing to start, sounds failing to play, etc)"};
73 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
74 static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", "maximum number of server information requests to send each rendered frame (guards against low framerates causing problems)"};
75 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
76 static cvar_t net_slist_maxtries = {0, "net_slist_maxtries", "3", "how many times to ask the same server for information (more times gives better ping reports but takes longer)"};
78 static cvar_t 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"};
80 /* statistic counters */
81 static int packetsSent = 0;
82 static int packetsReSent = 0;
83 static int packetsReceived = 0;
84 static int receivedDuplicateCount = 0;
85 static int droppedDatagrams = 0;
87 static int unreliableMessagesSent = 0;
88 static int unreliableMessagesReceived = 0;
89 static int reliableMessagesSent = 0;
90 static int reliableMessagesReceived = 0;
92 double masterquerytime = -1000;
93 int masterquerycount = 0;
94 int masterreplycount = 0;
95 int serverquerycount = 0;
96 int serverreplycount = 0;
98 // this is only false if there are still servers left to query
99 static qboolean serverlist_querysleep = true;
100 // this is pushed a second or two ahead of realtime whenever a master server
101 // reply is received, to avoid issuing queries while master replies are still
102 // flooding in (which would make a mess of the ping times)
103 static double serverlist_querywaittime = 0;
105 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
106 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
108 static int cl_numsockets;
109 static lhnetsocket_t *cl_sockets[16];
110 static int sv_numsockets;
111 static lhnetsocket_t *sv_sockets[16];
113 netconn_t *netconn_list = NULL;
114 mempool_t *netconn_mempool = NULL;
116 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
117 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
118 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
119 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
121 char net_extresponse[NET_EXTRESPONSE_MAX][1400];
122 int net_extresponse_count = 0;
123 int net_extresponse_last = 0;
125 // ServerList interface
126 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
127 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
129 serverlist_infofield_t serverlist_sortbyfield;
130 qboolean serverlist_sortdescending;
132 int serverlist_viewcount = 0;
133 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
135 int serverlist_cachecount;
136 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
138 qboolean serverlist_consoleoutput;
140 // helper function to insert a value into the viewset
141 // spare entries will be removed
142 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
145 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
146 i = serverlist_viewcount++;
148 i = SERVERLIST_VIEWLISTSIZE - 1;
151 for( ; i > index ; i-- )
152 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
154 serverlist_viewlist[index] = entry;
157 // we suppose serverlist_viewcount to be valid, ie > 0
158 static void _ServerList_ViewList_Helper_Remove( int index )
160 serverlist_viewcount--;
161 for( ; index < serverlist_viewcount ; index++ )
162 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
165 // returns true if A should be inserted before B
166 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
168 int result = 0; // > 0 if for numbers A > B and for text if A < B
170 switch( serverlist_sortbyfield ) {
172 result = A->info.ping - B->info.ping;
174 case SLIF_MAXPLAYERS:
175 result = A->info.maxplayers - B->info.maxplayers;
177 case SLIF_NUMPLAYERS:
178 result = A->info.numplayers - B->info.numplayers;
181 result = A->info.numbots - B->info.numbots;
184 result = A->info.numhumans - B->info.numhumans;
187 result = A->info.freeslots - B->info.freeslots;
190 result = A->info.protocol - B->info.protocol;
193 result = strcmp( B->info.cname, A->info.cname );
196 result = strcmp( B->info.game, A->info.game );
199 result = strcmp( B->info.map, A->info.map );
202 result = strcmp( B->info.mod, A->info.mod );
205 result = strcmp( B->info.name, A->info.name );
208 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
212 if( serverlist_sortdescending )
216 // if the chosen sort key is identical, sort by index
217 // (makes this a stable sort, so that later replies from servers won't
218 // shuffle the servers around when they have the same ping)
222 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
224 // This should actually be done with some intermediate and end-of-function return
236 case SLMO_GREATEREQUAL:
238 case SLMO_NOTCONTAIN:
241 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
246 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
249 char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
250 for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
251 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
253 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
254 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
257 // Same here, also using an intermediate & final return would be more appropriate
261 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
262 case SLMO_NOTCONTAIN:
263 return !*bufferB || !strstr( bufferA, bufferB );
265 return strcmp( bufferA, bufferB ) < 0;
267 return strcmp( bufferA, bufferB ) <= 0;
269 return strcmp( bufferA, bufferB ) == 0;
271 return strcmp( bufferA, bufferB ) > 0;
273 return strcmp( bufferA, bufferB ) != 0;
274 case SLMO_GREATEREQUAL:
275 return strcmp( bufferA, bufferB ) >= 0;
277 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
282 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
284 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
286 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
288 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
290 if( !_ServerList_CompareInt( info->numbots, mask->tests[SLIF_NUMBOTS], mask->info.numbots ) )
292 if( !_ServerList_CompareInt( info->numhumans, mask->tests[SLIF_NUMHUMANS], mask->info.numhumans ) )
294 if( !_ServerList_CompareInt( info->freeslots, mask->tests[SLIF_FREESLOTS], mask->info.freeslots ) )
296 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
298 if( *mask->info.cname
299 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
302 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
305 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
308 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
311 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
316 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
320 // reject incompatible servers
321 if (entry->info.gameversion != gameversion.integer)
324 // FIXME: change this to be more readable (...)
325 // now check whether it passes through the masks
326 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
327 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
330 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
331 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
333 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
336 if( !serverlist_viewcount ) {
337 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
340 // ok, insert it, we just need to find out where exactly:
343 // check whether to insert it as new first item
344 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
345 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
347 } // check whether to insert it as new last item
348 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
349 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
353 end = serverlist_viewcount - 1;
354 while( end > start + 1 )
356 mid = (start + end) / 2;
357 // test the item that lies in the middle between start and end
358 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
359 // the item has to be in the upper half
362 // the item has to be in the lower half
365 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
368 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
371 for( i = 0; i < serverlist_viewcount; i++ )
373 if (serverlist_viewlist[i] == entry)
375 _ServerList_ViewList_Helper_Remove(i);
381 void ServerList_RebuildViewList(void)
385 serverlist_viewcount = 0;
386 for( i = 0 ; i < serverlist_cachecount ; i++ ) {
387 serverlist_entry_t *entry = &serverlist_cache[i];
388 // also display entries that are currently being refreshed [11/8/2007 Black]
389 if( entry->query == SQS_QUERIED || entry->query == SQS_REFRESHING )
390 ServerList_ViewList_Insert( entry );
394 void ServerList_ResetMasks(void)
398 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
399 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
400 // numbots needs to be compared to -1 to always succeed
401 for(i = 0; i < SERVERLIST_ANDMASKCOUNT; ++i)
402 serverlist_andmasks[i].info.numbots = -1;
403 for(i = 0; i < SERVERLIST_ORMASKCOUNT; ++i)
404 serverlist_ormasks[i].info.numbots = -1;
407 void ServerList_GetPlayerStatistics(int *numplayerspointer, int *maxplayerspointer)
410 int numplayers = 0, maxplayers = 0;
411 for (i = 0;i < serverlist_cachecount;i++)
413 if (serverlist_cache[i].query == SQS_QUERIED)
415 numplayers += serverlist_cache[i].info.numhumans;
416 maxplayers += serverlist_cache[i].info.maxplayers;
419 *numplayerspointer = numplayers;
420 *maxplayerspointer = maxplayers;
424 static void _ServerList_Test(void)
427 for( i = 0 ; i < 1024 ; i++ ) {
428 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
429 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
430 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
431 serverlist_cache[serverlist_cachecount].finished = true;
432 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
433 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
434 serverlist_cachecount++;
439 void ServerList_QueryList(qboolean resetcache, qboolean querydp, qboolean queryqw, qboolean consoleoutput)
441 masterquerytime = realtime;
442 masterquerycount = 0;
443 masterreplycount = 0;
445 serverquerycount = 0;
446 serverreplycount = 0;
447 serverlist_cachecount = 0;
448 serverlist_viewcount = 0;
450 // refresh all entries
452 for( n = 0 ; n < serverlist_cachecount ; n++ ) {
453 serverlist_entry_t *entry = &serverlist_cache[ n ];
454 entry->query = SQS_REFRESHING;
455 entry->querycounter = 0;
458 serverlist_consoleoutput = consoleoutput;
460 //_ServerList_Test();
462 NetConn_QueryMasters(querydp, queryqw);
467 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
469 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
473 if (cl_netpacketloss_receive.integer)
474 for (i = 0;i < cl_numsockets;i++)
475 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_receive.integer)
477 if (developer_networking.integer)
479 char addressstring[128], addressstring2[128];
480 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
483 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
484 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
485 Com_HexDumpToConsole((unsigned char *)data, length);
488 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
493 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
497 if (cl_netpacketloss_send.integer)
498 for (i = 0;i < cl_numsockets;i++)
499 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss_send.integer)
501 ret = LHNET_Write(mysocket, data, length, peeraddress);
502 if (developer_networking.integer)
504 char addressstring[128], addressstring2[128];
505 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
506 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
507 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
508 Com_HexDumpToConsole((unsigned char *)data, length);
513 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
515 // note this does not include the trailing NULL because we add that in the parser
516 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
519 qboolean NetConn_CanSend(netconn_t *conn)
521 conn->outgoing_packetcounter = (conn->outgoing_packetcounter + 1) % NETGRAPH_PACKETS;
522 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
523 conn->outgoing_reliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
524 conn->outgoing_acksize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
525 if (realtime > conn->cleartime)
529 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_CHOKEDPACKET;
534 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
538 // if this packet was supposedly choked, but we find ourselves sending one
539 // anyway, make sure the size counting starts at zero
540 // (this mostly happens on level changes and disconnects and such)
541 if (conn->outgoing_unreliablesize[conn->outgoing_packetcounter] == NETGRAPH_CHOKEDPACKET)
542 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] = NETGRAPH_NOPACKET;
544 if (protocol == PROTOCOL_QUAKEWORLD)
547 qboolean sendreliable;
549 // note that it is ok to send empty messages to the qw server,
550 // otherwise it won't respond to us at all
552 sendreliable = false;
553 // if the remote side dropped the last reliable message, resend it
554 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
556 // if the reliable transmit buffer is empty, copy the current message out
557 if (!conn->sendMessageLength && conn->message.cursize)
559 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
560 conn->sendMessageLength = conn->message.cursize;
561 SZ_Clear(&conn->message); // clear the message buffer
562 conn->qw.reliable_sequence ^= 1;
565 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
566 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->qw.outgoing_sequence | ((unsigned int)sendreliable<<31));
567 // last received unreliable packet number, and last received reliable packet number (0 or 1)
568 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
570 conn->qw.outgoing_sequence++;
571 // client sends qport in every packet
572 if (conn == cls.netcon)
574 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
576 // also update cls.qw_outgoing_sequence
577 cls.qw_outgoing_sequence = conn->qw.outgoing_sequence;
579 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
581 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
585 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
587 // add the reliable message if there is one
590 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += conn->sendMessageLength;
591 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
592 packetLen += conn->sendMessageLength;
593 conn->qw.last_reliable_sequence = conn->qw.outgoing_sequence;
596 // add the unreliable message if possible
597 if (packetLen + data->cursize <= 1400)
599 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += data->cursize;
600 memcpy(sendbuffer + packetLen, data->data, data->cursize);
601 packetLen += data->cursize;
604 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
607 unreliableMessagesSent++;
609 totallen += packetLen + 28;
613 unsigned int packetLen;
614 unsigned int dataLen;
616 unsigned int *header;
618 // if a reliable message fragment has been lost, send it again
619 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
621 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
623 dataLen = conn->sendMessageLength;
628 dataLen = MAX_PACKETFRAGMENT;
632 packetLen = NET_HEADERSIZE + dataLen;
634 header = (unsigned int *)sendbuffer;
635 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
636 header[1] = BigLong(conn->nq.sendSequence - 1);
637 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
639 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
641 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
643 conn->lastSendTime = realtime;
647 totallen += packetLen + 28;
650 // if we have a new reliable message to send, do so
651 if (!conn->sendMessageLength && conn->message.cursize && !quakesignon_suppressreliables)
653 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
655 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, (int)sizeof(conn->sendMessage));
656 conn->message.overflowed = true;
660 if (developer_networking.integer && conn == cls.netcon)
662 Con_Print("client sending reliable message to server:\n");
663 SZ_HexDumpToConsole(&conn->message);
666 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
667 conn->sendMessageLength = conn->message.cursize;
668 SZ_Clear(&conn->message);
670 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
672 dataLen = conn->sendMessageLength;
677 dataLen = MAX_PACKETFRAGMENT;
681 packetLen = NET_HEADERSIZE + dataLen;
683 header = (unsigned int *)sendbuffer;
684 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
685 header[1] = BigLong(conn->nq.sendSequence);
686 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
688 conn->nq.sendSequence++;
690 conn->outgoing_reliablesize[conn->outgoing_packetcounter] += packetLen;
692 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
694 conn->lastSendTime = realtime;
696 reliableMessagesSent++;
698 totallen += packetLen + 28;
701 // if we have an unreliable message to send, do so
704 packetLen = NET_HEADERSIZE + data->cursize;
706 if (packetLen > (int)sizeof(sendbuffer))
708 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
712 header = (unsigned int *)sendbuffer;
713 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
714 header[1] = BigLong(conn->nq.unreliableSendSequence);
715 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
717 conn->nq.unreliableSendSequence++;
719 conn->outgoing_unreliablesize[conn->outgoing_packetcounter] += packetLen;
721 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
724 unreliableMessagesSent++;
726 totallen += packetLen + 28;
730 // delay later packets to obey rate limit
731 if (conn->cleartime < realtime - 0.1)
732 conn->cleartime = realtime - 0.1;
733 conn->cleartime = conn->cleartime + (double)totallen / (double)rate;
734 if (conn->cleartime < realtime)
735 conn->cleartime = realtime;
740 qboolean NetConn_HaveClientPorts(void)
742 return !!cl_numsockets;
745 qboolean NetConn_HaveServerPorts(void)
747 return !!sv_numsockets;
750 void NetConn_CloseClientPorts(void)
752 for (;cl_numsockets > 0;cl_numsockets--)
753 if (cl_sockets[cl_numsockets - 1])
754 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
757 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
759 lhnetaddress_t address;
761 char addressstring2[1024];
762 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
764 if ((s = LHNET_OpenSocket_Connectionless(&address)))
766 cl_sockets[cl_numsockets++] = s;
767 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
768 Con_Printf("Client opened a socket on address %s\n", addressstring2);
772 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
773 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
777 Con_Printf("Client unable to parse address %s\n", addressstring);
780 void NetConn_OpenClientPorts(void)
783 NetConn_CloseClientPorts();
784 port = bound(0, cl_netport.integer, 65535);
785 if (cl_netport.integer != port)
786 Cvar_SetValueQuick(&cl_netport, port);
787 Con_Printf("Client using port %i\n", port);
788 NetConn_OpenClientPort("local:2", 0);
789 NetConn_OpenClientPort(net_address.string, port);
790 //NetConn_OpenClientPort(net_address_ipv6.string, port);
793 void NetConn_CloseServerPorts(void)
795 for (;sv_numsockets > 0;sv_numsockets--)
796 if (sv_sockets[sv_numsockets - 1])
797 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
800 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
802 lhnetaddress_t address;
805 char addressstring2[1024];
807 for (port = defaultport; port <= defaultport + 100; port++)
809 if (LHNETADDRESS_FromString(&address, addressstring, port))
811 if ((s = LHNET_OpenSocket_Connectionless(&address)))
813 sv_sockets[sv_numsockets++] = s;
814 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
815 Con_Printf("Server listening on address %s\n", addressstring2);
820 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
821 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
826 Con_Printf("Server unable to parse address %s\n", addressstring);
827 // if it cant parse one address, it wont be able to parse another for sure
833 void NetConn_OpenServerPorts(int opennetports)
836 NetConn_CloseServerPorts();
837 NetConn_UpdateSockets();
838 port = bound(0, sv_netport.integer, 65535);
841 Con_Printf("Server using port %i\n", port);
842 if (sv_netport.integer != port)
843 Cvar_SetValueQuick(&sv_netport, port);
844 if (cls.state != ca_dedicated)
845 NetConn_OpenServerPort("local:1", 0);
848 NetConn_OpenServerPort(net_address.string, port);
849 //NetConn_OpenServerPort(net_address_ipv6.string, port);
851 if (sv_numsockets == 0)
852 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
855 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
857 int i, a = LHNETADDRESS_GetAddressType(address);
858 for (i = 0;i < cl_numsockets;i++)
859 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
860 return cl_sockets[i];
864 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
866 int i, a = LHNETADDRESS_GetAddressType(address);
867 for (i = 0;i < sv_numsockets;i++)
868 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
869 return sv_sockets[i];
873 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
876 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
877 conn->mysocket = mysocket;
878 conn->peeraddress = *peeraddress;
879 conn->lastMessageTime = realtime;
880 conn->message.data = conn->messagedata;
881 conn->message.maxsize = sizeof(conn->messagedata);
882 conn->message.cursize = 0;
883 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
884 // reduce effectiveness of connection request floods
885 conn->timeout = realtime + net_connecttimeout.value;
886 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
887 conn->next = netconn_list;
892 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress);
893 void NetConn_Close(netconn_t *conn)
896 // remove connection from list
898 // allow the client to reconnect immediately
899 NetConn_ClearConnectFlood(&(conn->peeraddress));
901 if (conn == netconn_list)
902 netconn_list = conn->next;
905 for (c = netconn_list;c;c = c->next)
909 c->next = conn->next;
913 // not found in list, we'll avoid crashing here...
921 static int clientport = -1;
922 static int clientport2 = -1;
923 static int hostport = -1;
924 void NetConn_UpdateSockets(void)
926 if (cls.state != ca_dedicated)
928 if (clientport2 != cl_netport.integer)
930 clientport2 = cl_netport.integer;
931 if (cls.state == ca_connected)
932 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
934 if (cls.state == ca_disconnected && clientport != clientport2)
936 clientport = clientport2;
937 NetConn_CloseClientPorts();
939 if (cl_numsockets == 0)
940 NetConn_OpenClientPorts();
943 if (hostport != sv_netport.integer)
945 hostport = sv_netport.integer;
947 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
951 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout)
953 int originallength = length;
957 if (protocol == PROTOCOL_QUAKEWORLD)
959 int sequence, sequence_ack;
960 int reliable_ack, reliable_message;
964 sequence = LittleLong(*((int *)(data + 0)));
965 sequence_ack = LittleLong(*((int *)(data + 4)));
969 if (conn != cls.netcon)
974 // 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?)
975 qport = LittleShort(*((int *)(data + 8)));
981 reliable_message = (sequence >> 31) & 1;
982 reliable_ack = (sequence_ack >> 31) & 1;
983 sequence &= ~(1<<31);
984 sequence_ack &= ~(1<<31);
985 if (sequence <= conn->qw.incoming_sequence)
987 //Con_DPrint("Got a stale datagram\n");
990 count = sequence - (conn->qw.incoming_sequence + 1);
993 droppedDatagrams += count;
994 //Con_DPrintf("Dropped %u datagram(s)\n", count);
997 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
998 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
999 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1000 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1003 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1004 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1005 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1006 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1007 if (reliable_ack == conn->qw.reliable_sequence)
1009 // received, now we will be able to send another reliable message
1010 conn->sendMessageLength = 0;
1011 reliableMessagesReceived++;
1013 conn->qw.incoming_sequence = sequence;
1014 if (conn == cls.netcon)
1015 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
1016 conn->qw.incoming_acknowledged = sequence_ack;
1017 conn->qw.incoming_reliable_acknowledged = reliable_ack;
1018 if (reliable_message)
1019 conn->qw.incoming_reliable_sequence ^= 1;
1020 conn->lastMessageTime = realtime;
1021 conn->timeout = realtime + newtimeout;
1022 unreliableMessagesReceived++;
1023 SZ_Clear(&net_message);
1024 SZ_Write(&net_message, data, length);
1032 unsigned int sequence;
1035 qlength = (unsigned int)BigLong(((int *)data)[0]);
1036 flags = qlength & ~NETFLAG_LENGTH_MASK;
1037 qlength &= NETFLAG_LENGTH_MASK;
1038 // control packets were already handled
1039 if (!(flags & NETFLAG_CTL) && qlength == length)
1041 sequence = BigLong(((int *)data)[1]);
1045 if (flags & NETFLAG_UNRELIABLE)
1047 if (sequence >= conn->nq.unreliableReceiveSequence)
1049 if (sequence > conn->nq.unreliableReceiveSequence)
1051 count = sequence - conn->nq.unreliableReceiveSequence;
1052 droppedDatagrams += count;
1053 //Con_DPrintf("Dropped %u datagram(s)\n", count);
1056 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1057 conn->incoming_unreliablesize[conn->incoming_packetcounter] = NETGRAPH_LOSTPACKET;
1058 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1059 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1062 conn->incoming_packetcounter = (conn->incoming_packetcounter + 1) % NETGRAPH_PACKETS;
1063 conn->incoming_unreliablesize[conn->incoming_packetcounter] = originallength;
1064 conn->incoming_reliablesize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1065 conn->incoming_acksize[conn->incoming_packetcounter] = NETGRAPH_NOPACKET;
1066 conn->nq.unreliableReceiveSequence = sequence + 1;
1067 conn->lastMessageTime = realtime;
1068 conn->timeout = realtime + newtimeout;
1069 unreliableMessagesReceived++;
1072 SZ_Clear(&net_message);
1073 SZ_Write(&net_message, data, length);
1079 // Con_DPrint("Got a stale datagram\n");
1082 else if (flags & NETFLAG_ACK)
1084 conn->incoming_acksize[conn->incoming_packetcounter] += originallength;
1085 if (sequence == (conn->nq.sendSequence - 1))
1087 if (sequence == conn->nq.ackSequence)
1089 conn->nq.ackSequence++;
1090 if (conn->nq.ackSequence != conn->nq.sendSequence)
1091 Con_DPrint("ack sequencing error\n");
1092 conn->lastMessageTime = realtime;
1093 conn->timeout = realtime + newtimeout;
1094 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
1096 unsigned int packetLen;
1097 unsigned int dataLen;
1099 unsigned int *header;
1101 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
1102 memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
1104 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
1106 dataLen = conn->sendMessageLength;
1111 dataLen = MAX_PACKETFRAGMENT;
1115 packetLen = NET_HEADERSIZE + dataLen;
1117 header = (unsigned int *)sendbuffer;
1118 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1119 header[1] = BigLong(conn->nq.sendSequence);
1120 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1122 conn->nq.sendSequence++;
1124 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1126 conn->lastSendTime = realtime;
1131 conn->sendMessageLength = 0;
1134 // Con_DPrint("Duplicate ACK received\n");
1137 // Con_DPrint("Stale ACK received\n");
1140 else if (flags & NETFLAG_DATA)
1142 unsigned int temppacket[2];
1143 conn->incoming_reliablesize[conn->incoming_packetcounter] += originallength;
1144 conn->outgoing_acksize[conn->outgoing_packetcounter] += 8;
1145 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1146 temppacket[1] = BigLong(sequence);
1147 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1148 if (sequence == conn->nq.receiveSequence)
1150 conn->lastMessageTime = realtime;
1151 conn->timeout = realtime + newtimeout;
1152 conn->nq.receiveSequence++;
1153 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1154 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1155 conn->receiveMessageLength += length;
1157 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1158 "Dropping the message!\n", sequence );
1159 conn->receiveMessageLength = 0;
1162 if (flags & NETFLAG_EOM)
1164 reliableMessagesReceived++;
1165 length = conn->receiveMessageLength;
1166 conn->receiveMessageLength = 0;
1169 SZ_Clear(&net_message);
1170 SZ_Write(&net_message, conn->receiveMessage, length);
1177 receivedDuplicateCount++;
1185 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1187 cls.connect_trying = false;
1188 M_Update_Return_Reason("");
1189 // the connection request succeeded, stop current connection and set up a new connection
1191 // if we're connecting to a remote server, shut down any local server
1192 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1193 Host_ShutdownServer ();
1194 // allocate a net connection to keep track of things
1195 cls.netcon = NetConn_Open(mysocket, peeraddress);
1196 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1197 key_dest = key_game;
1199 cls.demonum = -1; // not in the demo loop now
1200 cls.state = ca_connected;
1201 cls.signon = 0; // need all the signon messages before playing
1202 cls.protocol = initialprotocol;
1203 // reset move sequence numbering on this new connection
1204 cls.movesequence = 1;
1205 cls.servermovesequence = 0;
1206 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1207 Cmd_ForwardStringToServer("new");
1208 if (cls.protocol == PROTOCOL_QUAKE)
1210 // write a keepalive (clc_nop) as it seems to greatly improve the
1211 // chances of connecting to a netquake server
1213 unsigned char buf[4];
1214 memset(&msg, 0, sizeof(msg));
1216 msg.maxsize = sizeof(buf);
1217 MSG_WriteChar(&msg, clc_nop);
1218 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, false);
1222 int NetConn_IsLocalGame(void)
1224 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1229 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1233 serverlist_entry_t *entry = NULL;
1235 // search the cache for this server and update it
1236 for (n = 0;n < serverlist_cachecount;n++) {
1237 entry = &serverlist_cache[ n ];
1238 if (!strcmp(addressstring, entry->info.cname))
1242 if (n == serverlist_cachecount)
1244 // LAN search doesnt require an answer from the master server so we wont
1245 // know the ping nor will it be initialized already...
1248 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1251 entry = &serverlist_cache[n];
1253 memset(entry, 0, sizeof(*entry));
1254 // store the data the engine cares about (address and ping)
1255 strlcpy(entry->info.cname, addressstring, sizeof(entry->info.cname));
1256 entry->info.ping = 100000;
1257 entry->querytime = realtime;
1258 // if not in the slist menu we should print the server to console
1259 if (serverlist_consoleoutput)
1260 Con_Printf("querying %s\n", addressstring);
1261 ++serverlist_cachecount;
1263 // if this is the first reply from this server, count it as having replied
1264 pingtime = (int)((realtime - entry->querytime) * 1000.0 + 0.5);
1265 pingtime = bound(0, pingtime, 9999);
1266 if (entry->query == SQS_REFRESHING) {
1267 entry->info.ping = pingtime;
1268 entry->query = SQS_QUERIED;
1270 // convert to unsigned to catch the -1
1271 // 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]
1272 entry->info.ping = min((unsigned) entry->info.ping, (unsigned) pingtime);
1276 // other server info is updated by the caller
1280 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1282 serverlist_entry_t *entry = &serverlist_cache[n];
1283 serverlist_info_t *info = &entry->info;
1284 // update description strings for engine menu and console output
1285 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);
1286 dpsnprintf(entry->line2, sizeof(serverlist_cache[n].line2), "^4%-21.21s %-19.19s ^%c%-17.17s^4 %-20.20s", info->cname, info->game, (info->gameversion != gameversion.integer) ? '1' : '4', info->mod, info->map);
1287 if (entry->query == SQS_QUERIED)
1288 ServerList_ViewList_Remove(entry);
1289 // if not in the slist menu we should print the server to console (if wanted)
1290 else if( serverlist_consoleoutput )
1291 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1292 // and finally, update the view set
1293 ServerList_ViewList_Insert( entry );
1294 // update the entry's state
1295 serverlist_cache[n].query = SQS_QUERIED;
1298 // returns true, if it's sensible to continue the processing
1299 static qboolean NetConn_ClientParsePacket_ServerList_PrepareQuery( int protocol, const char *ipstring ) {
1301 serverlist_entry_t *entry;
1303 // ignore the rest of the message if the serverlist is full
1304 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1306 // also ignore it if we have already queried it (other master server response)
1307 for( n = 0 ; n < serverlist_cachecount ; n++ )
1308 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1311 entry = &serverlist_cache[n];
1313 if( n < serverlist_cachecount ) {
1314 // the entry has already been queried once or
1318 memset(entry, 0, sizeof(entry));
1319 entry->protocol = protocol;
1320 // store the data the engine cares about (address and ping)
1321 strlcpy (entry->info.cname, ipstring, sizeof(entry->info.cname));
1323 // no, then reset the ping right away
1324 entry->info.ping = -1;
1325 // we also want to increase the serverlist_cachecount then
1326 serverlist_cachecount++;
1329 entry->query = SQS_QUERYING;
1334 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1336 qboolean fromserver;
1337 int ret, c, control;
1339 char *string, addressstring2[128], ipstring[32];
1340 char stringbuf[16384];
1342 // quakeworld ingame packet
1343 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1345 // convert the address to a string incase we need it
1346 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1348 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1350 // received a command string - strip off the packaging and put it
1351 // into our string buffer with NULL termination
1354 length = min(length, (int)sizeof(stringbuf) - 1);
1355 memcpy(stringbuf, data, length);
1356 stringbuf[length] = 0;
1359 if (developer_networking.integer)
1361 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1362 Com_HexDumpToConsole(data, length);
1365 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1367 // darkplaces or quake3
1368 char protocolnames[1400];
1369 Protocol_Names(protocolnames, sizeof(protocolnames));
1370 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1371 M_Update_Return_Reason("Got challenge response");
1372 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1373 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1374 // TODO: add userinfo stuff here instead of using NQ commands?
1375 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1378 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1380 // darkplaces or quake3
1381 M_Update_Return_Reason("Accepted");
1382 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1385 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1387 char rejectreason[32];
1388 cls.connect_trying = false;
1390 length = max(length - 7, (int)sizeof(rejectreason) - 1);
1391 memcpy(rejectreason, string, length);
1392 rejectreason[length] = 0;
1393 M_Update_Return_Reason(rejectreason);
1396 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1398 serverlist_info_t *info;
1402 // search the cache for this server and update it
1403 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1407 info = &serverlist_cache[n].info;
1412 info->protocol = -1;
1413 info->numplayers = 0;
1415 info->maxplayers = 0;
1416 info->gameversion = 0;
1417 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));
1418 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));
1419 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));
1420 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));
1421 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);
1422 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);
1423 if ((s = SearchInfostring(string, "bots" )) != NULL) info->numbots = atoi(s);
1424 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);
1425 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);
1426 info->numhumans = info->numplayers - max(0, info->numbots);
1427 info->freeslots = info->maxplayers - info->numplayers;
1429 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1433 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1435 // Extract the IP addresses
1439 if (serverlist_consoleoutput)
1440 Con_Print("received DarkPlaces server list...\n");
1441 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1443 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1444 if (serverlist_consoleoutput && developer_networking.integer)
1445 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1447 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_DARKPLACES7, ipstring ) ) {
1451 // move on to next address in packet
1455 // begin or resume serverlist queries
1456 serverlist_querysleep = false;
1457 serverlist_querywaittime = realtime + 3;
1460 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1462 // Extract the IP addresses
1466 if (serverlist_consoleoutput)
1467 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1468 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1470 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1471 if (serverlist_consoleoutput && developer_networking.integer)
1472 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1474 if( !NetConn_ClientParsePacket_ServerList_PrepareQuery( PROTOCOL_QUAKEWORLD, ipstring ) ) {
1478 // move on to next address in packet
1482 // begin or resume serverlist queries
1483 serverlist_querysleep = false;
1484 serverlist_querywaittime = realtime + 3;
1487 if (!strncmp(string, "extResponse ", 12))
1489 ++net_extresponse_count;
1490 if(net_extresponse_count > NET_EXTRESPONSE_MAX)
1491 net_extresponse_count = NET_EXTRESPONSE_MAX;
1492 net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX;
1493 dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "'%s' %s", addressstring2, string + 12);
1496 if (!strncmp(string, "ping", 4))
1498 if (developer.integer >= 10)
1499 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1500 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1503 if (!strncmp(string, "ack", 3))
1505 // QuakeWorld compatibility
1506 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1508 // challenge message
1509 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1510 M_Update_Return_Reason("Got QuakeWorld challenge response");
1511 cls.qw_qport = qport.integer;
1512 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1513 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1514 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1517 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1520 M_Update_Return_Reason("QuakeWorld Accepted");
1521 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1524 if (length > 2 && !memcmp(string, "n\\", 2))
1526 serverlist_info_t *info;
1530 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1531 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1534 // search the cache for this server and update it
1535 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1539 info = &serverlist_cache[n].info;
1540 strlcpy(info->game, "QuakeWorld", sizeof(info->game));;
1541 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1542 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1543 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1545 info->numplayers = 0; // updated below
1546 info->numhumans = 0; // updated below
1547 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1548 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1550 // count active players on server
1551 // (we could gather more info, but we're just after the number)
1552 s = strchr(string, '\n');
1556 while (s < string + length)
1558 for (;s < string + length && *s != '\n';s++)
1560 if (s >= string + length)
1568 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1572 if (string[0] == 'n')
1575 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1577 // we may not have liked the packet, but it was a command packet, so
1578 // we're done processing this packet now
1581 // quakeworld ingame packet
1582 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1585 CL_ParseServerMessage();
1588 // netquake control packets, supported for compatibility only
1589 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1592 serverlist_info_t *info;
1596 SZ_Clear(&net_message);
1597 SZ_Write(&net_message, data, length);
1603 if (developer.integer >= 10)
1604 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1605 if (cls.connect_trying)
1607 lhnetaddress_t clientportaddress;
1608 clientportaddress = *peeraddress;
1609 LHNETADDRESS_SetPort(&clientportaddress, MSG_ReadLong());
1610 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1611 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1612 M_Update_Return_Reason("Accepted");
1613 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1617 if (developer.integer >= 10)
1618 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1619 cls.connect_trying = false;
1620 M_Update_Return_Reason((char *)MSG_ReadString());
1622 case CCREP_SERVER_INFO:
1623 if (developer.integer >= 10)
1624 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1625 // LordHavoc: because the quake server may report weird addresses
1626 // we just ignore it and keep the real address
1628 // search the cache for this server and update it
1629 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1633 info = &serverlist_cache[n].info;
1634 strlcpy(info->game, "Quake", sizeof(info->game));
1635 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1636 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1637 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1638 info->numplayers = MSG_ReadByte();
1639 info->maxplayers = MSG_ReadByte();
1640 info->protocol = MSG_ReadByte();
1642 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1645 case CCREP_PLAYER_INFO:
1646 // we got a CCREP_PLAYER_INFO??
1647 //if (developer.integer >= 10)
1648 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1650 case CCREP_RULE_INFO:
1651 // we got a CCREP_RULE_INFO??
1652 //if (developer.integer >= 10)
1653 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1658 SZ_Clear(&net_message);
1659 // we may not have liked the packet, but it was a valid control
1660 // packet, so we're done processing this packet now
1664 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2)
1665 CL_ParseServerMessage();
1669 void NetConn_QueryQueueFrame(void)
1675 static double querycounter = 0;
1677 if (serverlist_querysleep)
1680 // apply a cool down time after master server replies,
1681 // to avoid messing up the ping times on the servers
1682 if (serverlist_querywaittime > realtime)
1685 // each time querycounter reaches 1.0 issue a query
1686 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1687 maxqueries = (int)querycounter;
1688 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1689 querycounter -= maxqueries;
1691 if( maxqueries == 0 ) {
1695 // scan serverlist and issue queries as needed
1696 serverlist_querysleep = true;
1698 timeouttime = realtime - net_slist_timeout.value;
1699 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1701 serverlist_entry_t *entry = &serverlist_cache[ index ];
1702 if( entry->query != SQS_QUERYING && entry->query != SQS_REFRESHING )
1707 serverlist_querysleep = false;
1708 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1713 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1715 lhnetaddress_t address;
1718 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1719 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1721 for (socket = 0; socket < cl_numsockets ; socket++)
1722 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1726 for (socket = 0; socket < cl_numsockets ; socket++)
1727 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1730 // update the entry fields
1731 entry->querytime = realtime;
1732 entry->querycounter++;
1734 // if not in the slist menu we should print the server to console
1735 if (serverlist_consoleoutput)
1736 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1742 // have we tried to refresh this server?
1743 if( entry->query == SQS_REFRESHING ) {
1744 // yes, so update the reply count (since its not responding anymore)
1746 ServerList_ViewList_Remove(entry);
1748 entry->query = SQS_TIMEDOUT;
1753 void NetConn_ClientFrame(void)
1756 lhnetaddress_t peeraddress;
1757 NetConn_UpdateSockets();
1758 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1760 if (cls.connect_remainingtries == 0)
1761 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1762 cls.connect_nextsendtime = realtime + 1;
1763 cls.connect_remainingtries--;
1764 if (cls.connect_remainingtries <= -10)
1766 cls.connect_trying = false;
1767 M_Update_Return_Reason("Connect: Failed");
1770 // try challenge first (newer DP server or QW)
1771 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1772 // then try netquake as a fallback (old server, or netquake)
1773 SZ_Clear(&net_message);
1774 // save space for the header, filled in later
1775 MSG_WriteLong(&net_message, 0);
1776 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1777 MSG_WriteString(&net_message, "QUAKE");
1778 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1779 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1780 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1781 SZ_Clear(&net_message);
1783 for (i = 0;i < cl_numsockets;i++)
1784 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1785 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1786 NetConn_QueryQueueFrame();
1787 if (cls.netcon && realtime > cls.netcon->timeout && !sv.active)
1789 Con_Print("Connection timed out\n");
1791 Host_ShutdownServer ();
1795 #define MAX_CHALLENGES 128
1798 lhnetaddress_t address;
1802 challenge[MAX_CHALLENGES];
1804 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1808 for (i = 0;i < bufferlength - 1;i++)
1812 c = rand () % (127 - 33) + 33;
1813 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1819 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1821 unsigned int nb_clients = 0, nb_bots = 0, i;
1824 // How many clients are there?
1825 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1827 if (svs.clients[i].active)
1830 if (!svs.clients[i].netconnection)
1835 // TODO: we should add more information for the full status string
1836 length = dpsnprintf(out_msg, out_size,
1837 "\377\377\377\377%s\x0A"
1838 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1839 "\\clients\\%d\\bots\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1842 fullstatus ? "statusResponse" : "infoResponse",
1843 gamename, com_modname, gameversion.integer, svs.maxclients,
1844 nb_clients, nb_bots, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1845 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1846 fullstatus ? "\n" : "");
1848 // Make sure it fits in the buffer
1857 ptr = out_msg + length;
1858 left = (int)out_size - length;
1860 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1862 client_t *cl = &svs.clients[i];
1865 int nameind, cleanind, pingvalue;
1867 char cleanname [sizeof(cl->name)];
1869 // Remove all characters '"' and '\' in the player name
1874 curchar = cl->name[nameind++];
1875 if (curchar != '"' && curchar != '\\')
1877 cleanname[cleanind++] = curchar;
1878 if (cleanind == sizeof(cleanname) - 1)
1881 } while (curchar != '\0');
1883 pingvalue = (int)(cl->ping * 1000.0f);
1884 if(cl->netconnection)
1885 pingvalue = bound(1, pingvalue, 9999);
1888 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1903 static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress)
1905 int floodslotnum, bestfloodslotnum;
1906 double bestfloodtime;
1907 lhnetaddress_t noportpeeraddress;
1908 // see if this is a connect flood
1909 noportpeeraddress = *peeraddress;
1910 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1911 bestfloodslotnum = 0;
1912 bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime;
1913 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1915 if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime)
1917 bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime;
1918 bestfloodslotnum = floodslotnum;
1920 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1922 // this address matches an ongoing flood address
1923 if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value)
1925 // renew the ban on this address so it does not expire
1926 // until the flood has subsided
1927 sv.connectfloodaddresses[floodslotnum].lasttime = realtime;
1928 //Con_Printf("Flood detected!\n");
1931 // the flood appears to have subsided, so allow this
1932 bestfloodslotnum = floodslotnum; // reuse the same slot
1936 // begin a new timeout on this address
1937 sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress;
1938 sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime;
1939 //Con_Printf("Flood detection initiated!\n");
1943 void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress)
1946 lhnetaddress_t noportpeeraddress;
1947 // see if this is a connect flood
1948 noportpeeraddress = *peeraddress;
1949 LHNETADDRESS_SetPort(&noportpeeraddress, 0);
1950 for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++)
1952 if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0)
1954 // this address matches an ongoing flood address
1956 sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE;
1957 sv.connectfloodaddresses[floodslotnum].lasttime = 0;
1958 //Con_Printf("Flood cleared!\n");
1963 extern void SV_SendServerinfo (client_t *client);
1964 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1966 int i, ret, clientnum, best;
1969 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1970 qboolean islocal = (LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP);
1975 // convert the address to a string incase we need it
1976 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1978 // see if we can identify the sender as a local player
1979 // (this is necessary for rcon to send a reliable reply if the client is
1980 // actually on the server, not sending remotely)
1981 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1982 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1984 if (i == svs.maxclients)
1987 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1989 // received a command string - strip off the packaging and put it
1990 // into our string buffer with NULL termination
1993 length = min(length, (int)sizeof(stringbuf) - 1);
1994 memcpy(stringbuf, data, length);
1995 stringbuf[length] = 0;
1998 if (developer.integer >= 10)
2000 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
2001 Com_HexDumpToConsole(data, length);
2004 if (length >= 12 && !memcmp(string, "getchallenge", 12) && (islocal || sv_public.integer > -2))
2006 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
2008 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
2010 if (besttime > challenge[i].time)
2011 besttime = challenge[best = i].time;
2013 // if we did not find an exact match, choose the oldest and
2014 // update address and string
2015 if (i == MAX_CHALLENGES)
2018 challenge[i].address = *peeraddress;
2019 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
2021 challenge[i].time = realtime;
2022 // send the challenge
2023 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
2026 if (length > 8 && !memcmp(string, "connect\\", 8) && (islocal || sv_public.integer > -2))
2031 if (!(s = SearchInfostring(string, "challenge")))
2033 // validate the challenge
2034 for (i = 0;i < MAX_CHALLENGES;i++)
2035 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
2037 // if the challenge is not recognized, drop the packet
2038 if (i == MAX_CHALLENGES)
2041 // check engine protocol
2042 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
2044 if (developer.integer >= 10)
2045 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
2046 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
2050 // see if this is a duplicate connection request or a disconnected
2051 // client who is rejoining to the same client slot
2052 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2054 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2056 // this is a known client...
2057 if (client->spawned)
2059 // client crashed and is coming back,
2060 // keep their stuff intact
2061 if (developer.integer >= 10)
2062 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2);
2063 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2065 SV_SendServerinfo(client);
2070 // client is still trying to connect,
2071 // so we send a duplicate reply
2072 if (developer.integer >= 10)
2073 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
2074 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2080 if (NetConn_PreventConnectFlood(peeraddress))
2083 // find an empty client slot for this new client
2084 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2087 if (!client->active && (conn = NetConn_Open(mysocket, peeraddress)))
2089 // allocated connection
2090 if (developer.integer >= 10)
2091 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
2092 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
2093 // now set up the client
2095 SV_ConnectClient(clientnum, conn);
2097 NetConn_Heartbeat(1);
2102 // no empty slots found - server is full
2103 if (developer.integer >= 10)
2104 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
2105 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
2109 if (length >= 7 && !memcmp(string, "getinfo", 7) && (islocal || sv_public.integer > -1))
2111 const char *challenge = NULL;
2113 // If there was a challenge in the getinfo message
2114 if (length > 8 && string[7] == ' ')
2115 challenge = string + 8;
2117 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
2119 if (developer.integer >= 10)
2120 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
2121 NetConn_WriteString(mysocket, response, peeraddress);
2125 if (length >= 9 && !memcmp(string, "getstatus", 9) && (islocal || sv_public.integer > -1))
2127 const char *challenge = NULL;
2129 // If there was a challenge in the getinfo message
2130 if (length > 10 && string[9] == ' ')
2131 challenge = string + 10;
2133 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
2135 if (developer.integer >= 10)
2136 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
2137 NetConn_WriteString(mysocket, response, peeraddress);
2141 if (length >= 5 && !memcmp(string, "rcon ", 5))
2144 char *s = string + 5;
2145 char *endpos = string + length + 1; // one behind the NUL, so adding strlen+1 will eventually reach it
2147 for (i = 0;*s > ' ';s++)
2148 if (i < (int)sizeof(password) - 1)
2150 if(*s <= ' ' && s != endpos) // skip leading ugly space
2153 if (password[0] > ' ' && !strcmp(rcon_password.string, password))
2155 // looks like a legitimate rcon command with the correct password
2157 Con_Printf("server received rcon command from %s:\n", host_client ? host_client->name : addressstring2);
2158 while(s_ptr != endpos)
2160 size_t l = strlen(s_ptr);
2162 Con_Printf(" %s;", s_ptr);
2166 rcon_redirect = true;
2167 rcon_redirect_bufferpos = 0;
2170 size_t l = strlen(s);
2172 Cmd_ExecuteString(s, src_command);
2175 rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
2176 rcon_redirect = false;
2177 // print resulting text to client
2178 // if client is playing, send a reliable reply instead of
2182 // if the netconnection is loop, then this is the
2183 // local player on a listen mode server, and it would
2184 // result in duplicate printing to the console
2185 // (not that the local player should be using rcon
2186 // when they have the console)
2187 if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2188 SV_ClientPrintf("%s", rcon_redirect_buffer);
2193 dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
2194 NetConn_WriteString(mysocket, response, peeraddress);
2199 if (!strncmp(string, "ping", 4))
2201 if (developer.integer >= 10)
2202 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
2203 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
2206 if (!strncmp(string, "ack", 3))
2208 // we may not have liked the packet, but it was a command packet, so
2209 // we're done processing this packet now
2212 // netquake control packets, supported for compatibility only, and only
2213 // when running game protocols that are normally served via this connection
2215 // (this protects more modern protocols against being used for
2216 // Quake packet flood Denial Of Service attacks)
2217 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))
2221 const char *protocolname;
2224 SZ_Clear(&net_message);
2225 SZ_Write(&net_message, data, length);
2231 if (developer.integer >= 10)
2232 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
2233 if(!islocal && sv_public.integer <= -2)
2236 protocolname = MSG_ReadString();
2237 protocolnumber = MSG_ReadByte();
2238 if (strcmp(protocolname, "QUAKE") || protocolnumber != NET_PROTOCOL_VERSION)
2240 if (developer.integer >= 10)
2241 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
2242 SZ_Clear(&net_message);
2243 // save space for the header, filled in later
2244 MSG_WriteLong(&net_message, 0);
2245 MSG_WriteByte(&net_message, CCREP_REJECT);
2246 MSG_WriteString(&net_message, "Incompatible version.\n");
2247 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2248 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2249 SZ_Clear(&net_message);
2253 // see if this connect request comes from a known client
2254 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2256 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
2258 // this is either a duplicate connection request
2259 // or coming back from a timeout
2260 // (if so, keep their stuff intact)
2263 if (developer.integer >= 10)
2264 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
2265 SZ_Clear(&net_message);
2266 // save space for the header, filled in later
2267 MSG_WriteLong(&net_message, 0);
2268 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2269 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
2270 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2271 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2272 SZ_Clear(&net_message);
2274 // if client is already spawned, re-send the
2275 // serverinfo message as they'll need it to play
2276 if (client->spawned)
2279 SV_SendServerinfo(client);
2286 // this is a new client, check for connection flood
2287 if (NetConn_PreventConnectFlood(peeraddress))
2290 // find a slot for the new client
2291 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2294 if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2296 // connect to the client
2297 // everything is allocated, just fill in the details
2298 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2299 if (developer.integer >= 10)
2300 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2301 // send back the info about the server connection
2302 SZ_Clear(&net_message);
2303 // save space for the header, filled in later
2304 MSG_WriteLong(&net_message, 0);
2305 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2306 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2307 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2308 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2309 SZ_Clear(&net_message);
2310 // now set up the client struct
2312 SV_ConnectClient(clientnum, conn);
2314 NetConn_Heartbeat(1);
2319 if (developer.integer >= 10)
2320 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2321 // no room; try to let player know
2322 SZ_Clear(&net_message);
2323 // save space for the header, filled in later
2324 MSG_WriteLong(&net_message, 0);
2325 MSG_WriteByte(&net_message, CCREP_REJECT);
2326 MSG_WriteString(&net_message, "Server is full.\n");
2327 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2328 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2329 SZ_Clear(&net_message);
2331 case CCREQ_SERVER_INFO:
2332 if (developer.integer >= 10)
2333 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2334 if(!islocal && sv_public.integer <= -1)
2336 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2339 char myaddressstring[128];
2340 if (developer.integer >= 10)
2341 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2342 SZ_Clear(&net_message);
2343 // save space for the header, filled in later
2344 MSG_WriteLong(&net_message, 0);
2345 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2346 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2347 MSG_WriteString(&net_message, myaddressstring);
2348 MSG_WriteString(&net_message, hostname.string);
2349 MSG_WriteString(&net_message, sv.name);
2350 // How many clients are there?
2351 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2352 if (svs.clients[i].active)
2354 MSG_WriteByte(&net_message, numclients);
2355 MSG_WriteByte(&net_message, svs.maxclients);
2356 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2357 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2358 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2359 SZ_Clear(&net_message);
2362 case CCREQ_PLAYER_INFO:
2363 if (developer.integer >= 10)
2364 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2365 if(!islocal && sv_public.integer <= -1)
2369 int playerNumber, activeNumber, clientNumber;
2372 playerNumber = MSG_ReadByte();
2374 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2375 if (client->active && ++activeNumber == playerNumber)
2377 if (clientNumber != svs.maxclients)
2379 SZ_Clear(&net_message);
2380 // save space for the header, filled in later
2381 MSG_WriteLong(&net_message, 0);
2382 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2383 MSG_WriteByte(&net_message, playerNumber);
2384 MSG_WriteString(&net_message, client->name);
2385 MSG_WriteLong(&net_message, client->colors);
2386 MSG_WriteLong(&net_message, client->frags);
2387 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2388 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2389 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2390 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2391 SZ_Clear(&net_message);
2395 case CCREQ_RULE_INFO:
2396 if (developer.integer >= 10)
2397 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2398 if(!islocal && sv_public.integer <= -1)
2405 // find the search start location
2406 prevCvarName = MSG_ReadString();
2407 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2409 // send the response
2410 SZ_Clear(&net_message);
2411 // save space for the header, filled in later
2412 MSG_WriteLong(&net_message, 0);
2413 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2416 MSG_WriteString(&net_message, var->name);
2417 MSG_WriteString(&net_message, var->string);
2419 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2420 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2421 SZ_Clear(&net_message);
2427 SZ_Clear(&net_message);
2428 // we may not have liked the packet, but it was a valid control
2429 // packet, so we're done processing this packet now
2434 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2)
2437 SV_ReadClientMessage();
2445 void NetConn_ServerFrame(void)
2448 lhnetaddress_t peeraddress;
2449 for (i = 0;i < sv_numsockets;i++)
2450 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2451 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2452 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2454 // never timeout loopback connections
2455 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2457 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2459 SV_DropClient(false);
2465 void NetConn_SleepMicroseconds(int microseconds)
2467 LHNET_SleepUntilPacket_Microseconds(microseconds);
2470 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2474 lhnetaddress_t masteraddress;
2475 lhnetaddress_t broadcastaddress;
2478 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2481 // 26000 is the default quake server port, servers on other ports will not
2483 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2484 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2488 for (i = 0;i < cl_numsockets;i++)
2492 // search LAN for Quake servers
2493 SZ_Clear(&net_message);
2494 // save space for the header, filled in later
2495 MSG_WriteLong(&net_message, 0);
2496 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2497 MSG_WriteString(&net_message, "QUAKE");
2498 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2499 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2500 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2501 SZ_Clear(&net_message);
2503 // search LAN for DarkPlaces servers
2504 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2506 // build the getservers message to send to the dpmaster master servers
2507 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2510 for (masternum = 0;sv_masters[masternum].name;masternum++)
2512 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])))
2515 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2522 // only query QuakeWorld servers when the user wants to
2525 for (i = 0;i < cl_numsockets;i++)
2529 // search LAN for QuakeWorld servers
2530 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2532 // build the getservers message to send to the qwmaster master servers
2533 // note this has no -1 prefix, and the trailing nul byte is sent
2534 dpsnprintf(request, sizeof(request), "c\n");
2537 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2539 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2541 if (m_state != m_slist)
2543 char lookupstring[128];
2544 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2545 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2548 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2554 if (!masterquerycount)
2556 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2557 M_Update_Return_Reason("No network");
2561 void NetConn_Heartbeat(int priority)
2563 lhnetaddress_t masteraddress;
2565 lhnetsocket_t *mysocket;
2567 // if it's a state change (client connected), limit next heartbeat to no
2568 // more than 30 sec in the future
2569 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2570 nextheartbeattime = realtime + 30.0;
2572 // limit heartbeatperiod to 30 to 270 second range,
2573 // lower limit is to avoid abusing master servers with excess traffic,
2574 // upper limit is to avoid timing out on the master server (which uses
2576 if (sv_heartbeatperiod.value < 30)
2577 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2578 if (sv_heartbeatperiod.value > 270)
2579 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2581 // make advertising optional and don't advertise singleplayer games, and
2582 // only send a heartbeat as often as the admin wants
2583 if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2585 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2586 for (masternum = 0;sv_masters[masternum].name;masternum++)
2587 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2588 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2592 static void Net_Heartbeat_f(void)
2595 NetConn_Heartbeat(2);
2597 Con_Print("No server running, can not heartbeat to master server.\n");
2600 void PrintStats(netconn_t *conn)
2602 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2603 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2605 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2608 void Net_Stats_f(void)
2611 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2612 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2613 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2614 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2615 Con_Printf("packetsSent = %i\n", packetsSent);
2616 Con_Printf("packetsReSent = %i\n", packetsReSent);
2617 Con_Printf("packetsReceived = %i\n", packetsReceived);
2618 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2619 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2620 Con_Print("connections =\n");
2621 for (conn = netconn_list;conn;conn = conn->next)
2625 void Net_Refresh_f(void)
2627 if (m_state != m_slist) {
2628 Con_Print("Sending new requests to master servers\n");
2629 ServerList_QueryList(false, true, false, true);
2630 Con_Print("Listening for replies...\n");
2632 ServerList_QueryList(false, true, false, false);
2635 void Net_Slist_f(void)
2637 ServerList_ResetMasks();
2638 serverlist_sortbyfield = SLIF_PING;
2639 serverlist_sortdescending = false;
2640 if (m_state != m_slist) {
2641 Con_Print("Sending requests to master servers\n");
2642 ServerList_QueryList(true, true, false, true);
2643 Con_Print("Listening for replies...\n");
2645 ServerList_QueryList(true, true, false, false);
2648 void Net_SlistQW_f(void)
2650 ServerList_ResetMasks();
2651 serverlist_sortbyfield = SLIF_PING;
2652 serverlist_sortdescending = false;
2653 if (m_state != m_slist) {
2654 Con_Print("Sending requests to master servers\n");
2655 ServerList_QueryList(true, false, true, true);
2656 serverlist_consoleoutput = true;
2657 Con_Print("Listening for replies...\n");
2659 ServerList_QueryList(true, false, true, false);
2662 void NetConn_Init(void)
2665 lhnetaddress_t tempaddress;
2666 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2667 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2668 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2669 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2670 Cmd_AddCommand("net_refresh", Net_Refresh_f, "query dp master servers and refresh all server information");
2671 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2672 Cvar_RegisterVariable(&net_slist_queriespersecond);
2673 Cvar_RegisterVariable(&net_slist_queriesperframe);
2674 Cvar_RegisterVariable(&net_slist_timeout);
2675 Cvar_RegisterVariable(&net_slist_maxtries);
2676 Cvar_RegisterVariable(&net_messagetimeout);
2677 Cvar_RegisterVariable(&net_connecttimeout);
2678 Cvar_RegisterVariable(&net_connectfloodblockingtimeout);
2679 Cvar_RegisterVariable(&cl_netlocalping);
2680 Cvar_RegisterVariable(&cl_netpacketloss_send);
2681 Cvar_RegisterVariable(&cl_netpacketloss_receive);
2682 Cvar_RegisterVariable(&hostname);
2683 Cvar_RegisterVariable(&developer_networking);
2684 Cvar_RegisterVariable(&cl_netport);
2685 Cvar_RegisterVariable(&sv_netport);
2686 Cvar_RegisterVariable(&net_address);
2687 //Cvar_RegisterVariable(&net_address_ipv6);
2688 Cvar_RegisterVariable(&sv_public);
2689 Cvar_RegisterVariable(&sv_heartbeatperiod);
2690 for (i = 0;sv_masters[i].name;i++)
2691 Cvar_RegisterVariable(&sv_masters[i]);
2692 Cvar_RegisterVariable(&gameversion);
2693 // 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.
2694 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2696 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2698 Con_Printf("-ip option used, setting net_address to \"%s\"\n", com_argv[i + 1]);
2699 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2702 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2704 // 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
2705 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2707 i = atoi(com_argv[i + 1]);
2708 if (i >= 0 && i < 65536)
2710 Con_Printf("-port option used, setting port cvar to %i\n", i);
2711 Cvar_SetValueQuick(&sv_netport, i);
2714 Con_Printf("-port option used, but %i is not a valid port number\n", i);
2718 net_message.data = net_message_buf;
2719 net_message.maxsize = sizeof(net_message_buf);
2720 net_message.cursize = 0;
2724 void NetConn_Shutdown(void)
2726 NetConn_CloseClientPorts();
2727 NetConn_CloseServerPorts();