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", "advertises this server on the master server (so that players can find it in the server browser)"};
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", "12.166.196.192", "default master server 3 (admin: Venim)"}, // admin: Venim
42 {0, "sv_masterextra4", "excalibur.nvg.ntnu.no", "default master server 4 (admin: tChr)"}, // admin: tChr
46 static cvar_t sv_qwmasters [] =
48 {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"},
49 {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"},
50 {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"},
51 {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"},
52 {0, "sv_qwmasterextra1", "192.246.40.37:27000", "id Limbo (admin: id Software)"},
53 {0, "sv_qwmasterextra2", "192.246.40.37:27002", "id CTF (admin: id Software)"},
54 {0, "sv_qwmasterextra3", "192.246.40.37:27003", "id TeamFortress (admin: id Software)"},
55 {0, "sv_qwmasterextra4", "192.246.40.37:27004", "id Miscilaneous (admin: id Software)"},
56 {0, "sv_qwmasterextra5", "192.246.40.37:27006", "id Deathmatch Only (admin: id Software)"},
57 {0, "sv_qwmasterextra6", "150.254.66.120:27000", "Poland's master server. (admin: unknown)"},
58 {0, "sv_qwmasterextra7", "62.112.145.129:27000", "Ocrana master server. (admin: unknown)"},
59 {0, "sv_qwmasterextra8", "master.edome.net", "edome master server. (admin: unknown)"},
60 {0, "sv_qwmasterextra9", "qwmaster.barrysworld.com", "barrysworld master server. (admin: unknown)"},
61 {0, "sv_qwmasterextra10", "qwmaster.ocrana.de:27000", "Ocrana2 master server. (admin: unknown)"},
62 {0, "sv_qwmasterextra11", "213.221.174.165:27000", "unknown1 master server. (admin: unknown)"},
63 {0, "sv_qwmasterextra12", "195.74.0.8", "unknown2 master server. (admin: unknown)"},
64 {0, "sv_qwmasterextra13", "204.182.161.2", "unknown3 master server. (admin: unknown)"},
68 static double nextheartbeattime = 0;
70 sizebuf_t net_message;
71 static unsigned char net_message_buf[NET_MAXMESSAGE];
73 cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"};
74 cvar_t net_messagerejointimeout = {0, "net_messagerejointimeout","10", "give a player this much time in seconds to rejoin and continue playing (not losing frags and such)"};
75 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)"};
76 cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"};
77 cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"};
79 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)"};
80 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)"};
81 static cvar_t net_slist_queriespersecond = {0, "net_slist_queriespersecond", "20", "how many server information requests to send per second"};
82 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)"};
83 static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"};
84 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)"};
86 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"};
88 /* statistic counters */
89 static int packetsSent = 0;
90 static int packetsReSent = 0;
91 static int packetsReceived = 0;
92 static int receivedDuplicateCount = 0;
93 static int droppedDatagrams = 0;
95 static int unreliableMessagesSent = 0;
96 static int unreliableMessagesReceived = 0;
97 static int reliableMessagesSent = 0;
98 static int reliableMessagesReceived = 0;
100 double masterquerytime = -1000;
101 int masterquerycount = 0;
102 int masterreplycount = 0;
103 int serverquerycount = 0;
104 int serverreplycount = 0;
106 // this is only false if there are still servers left to query
107 static qboolean serverlist_querysleep = true;
108 // this is pushed a second or two ahead of realtime whenever a master server
109 // reply is received, to avoid issuing queries while master replies are still
110 // flooding in (which would make a mess of the ping times)
111 static double serverlist_querywaittime = 0;
113 static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
114 static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE];
116 static int cl_numsockets;
117 static lhnetsocket_t *cl_sockets[16];
118 static int sv_numsockets;
119 static lhnetsocket_t *sv_sockets[16];
121 netconn_t *netconn_list = NULL;
122 mempool_t *netconn_mempool = NULL;
124 cvar_t cl_netport = {0, "cl_port", "0", "forces client to use chosen port number if not 0"};
125 cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to"};
126 cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"};
127 //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"};
129 // ServerList interface
130 serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT];
131 serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT];
133 serverlist_infofield_t serverlist_sortbyfield;
134 qboolean serverlist_sortdescending;
136 int serverlist_viewcount = 0;
137 serverlist_entry_t *serverlist_viewlist[SERVERLIST_VIEWLISTSIZE];
139 int serverlist_cachecount;
140 serverlist_entry_t serverlist_cache[SERVERLIST_TOTALSIZE];
142 qboolean serverlist_consoleoutput;
144 // helper function to insert a value into the viewset
145 // spare entries will be removed
146 static void _ServerList_ViewList_Helper_InsertBefore( int index, serverlist_entry_t *entry )
149 if( serverlist_viewcount < SERVERLIST_VIEWLISTSIZE ) {
150 i = serverlist_viewcount++;
152 i = SERVERLIST_VIEWLISTSIZE - 1;
155 for( ; i > index ; i-- )
156 serverlist_viewlist[ i ] = serverlist_viewlist[ i - 1 ];
158 serverlist_viewlist[index] = entry;
161 // we suppose serverlist_viewcount to be valid, ie > 0
162 static void _ServerList_ViewList_Helper_Remove( int index )
164 serverlist_viewcount--;
165 for( ; index < serverlist_viewcount ; index++ )
166 serverlist_viewlist[index] = serverlist_viewlist[index + 1];
169 // returns true if A should be inserted before B
170 static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_entry_t *B )
172 int result = 0; // > 0 if for numbers A > B and for text if A < B
174 switch( serverlist_sortbyfield ) {
176 result = A->info.ping - B->info.ping;
178 case SLIF_MAXPLAYERS:
179 result = A->info.maxplayers - B->info.maxplayers;
181 case SLIF_NUMPLAYERS:
182 result = A->info.numplayers - B->info.numplayers;
185 result = A->info.protocol - B->info.protocol;
188 result = strcmp( B->info.cname, A->info.cname );
191 result = strcmp( B->info.game, A->info.game );
194 result = strcmp( B->info.map, A->info.map );
197 result = strcmp( B->info.mod, A->info.mod );
200 result = strcmp( B->info.name, A->info.name );
203 Con_DPrint( "_ServerList_Entry_Compare: Bad serverlist_sortbyfield!\n" );
207 if( serverlist_sortdescending )
211 // if the chosen sort key is identical, sort by index
212 // (makes this a stable sort, so that later replies from servers won't
213 // shuffle the servers around when they have the same ping)
217 static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B )
219 // This should actually be done with some intermediate and end-of-function return
231 case SLMO_GREATEREQUAL:
233 case SLMO_NOTCONTAIN:
236 Con_DPrint( "_ServerList_CompareInt: Bad op!\n" );
241 static qboolean _ServerList_CompareStr( const char *A, serverlist_maskop_t op, const char *B )
244 char bufferA[ 256 ], bufferB[ 256 ]; // should be more than enough
245 for (i = 0;i < (int)sizeof(bufferA)-1 && A[i];i++)
246 bufferA[i] = (A[i] >= 'A' && A[i] <= 'Z') ? (A[i] + 'a' - 'A') : A[i];
248 for (i = 0;i < (int)sizeof(bufferB)-1 && B[i];i++)
249 bufferB[i] = (B[i] >= 'A' && B[i] <= 'Z') ? (B[i] + 'a' - 'A') : B[i];
252 // Same here, also using an intermediate & final return would be more appropriate
256 return *bufferB && !!strstr( bufferA, bufferB ); // we want a real bool
257 case SLMO_NOTCONTAIN:
258 return !*bufferB || !strstr( bufferA, bufferB );
260 return strcmp( bufferA, bufferB ) < 0;
262 return strcmp( bufferA, bufferB ) <= 0;
264 return strcmp( bufferA, bufferB ) == 0;
266 return strcmp( bufferA, bufferB ) > 0;
268 return strcmp( bufferA, bufferB ) != 0;
269 case SLMO_GREATEREQUAL:
270 return strcmp( bufferA, bufferB ) >= 0;
272 Con_DPrint( "_ServerList_CompareStr: Bad op!\n" );
277 static qboolean _ServerList_Entry_Mask( serverlist_mask_t *mask, serverlist_info_t *info )
279 if( !_ServerList_CompareInt( info->ping, mask->tests[SLIF_PING], mask->info.ping ) )
281 if( !_ServerList_CompareInt( info->maxplayers, mask->tests[SLIF_MAXPLAYERS], mask->info.maxplayers ) )
283 if( !_ServerList_CompareInt( info->numplayers, mask->tests[SLIF_NUMPLAYERS], mask->info.numplayers ) )
285 if( !_ServerList_CompareInt( info->protocol, mask->tests[SLIF_PROTOCOL], mask->info.protocol ))
287 if( *mask->info.cname
288 && !_ServerList_CompareStr( info->cname, mask->tests[SLIF_CNAME], mask->info.cname ) )
291 && !_ServerList_CompareStr( info->game, mask->tests[SLIF_GAME], mask->info.game ) )
294 && !_ServerList_CompareStr( info->mod, mask->tests[SLIF_MOD], mask->info.mod ) )
297 && !_ServerList_CompareStr( info->map, mask->tests[SLIF_MAP], mask->info.map ) )
300 && !_ServerList_CompareStr( info->name, mask->tests[SLIF_NAME], mask->info.name ) )
305 static void ServerList_ViewList_Insert( serverlist_entry_t *entry )
309 // reject incompatible servers
310 if (entry->info.gameversion != gameversion.integer)
313 // FIXME: change this to be more readable (...)
314 // now check whether it passes through the masks
315 for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ )
316 if( !_ServerList_Entry_Mask( &serverlist_andmasks[start], &entry->info ) )
319 for( start = 0 ; serverlist_ormasks[start].active && start < SERVERLIST_ORMASKCOUNT ; start++ )
320 if( _ServerList_Entry_Mask( &serverlist_ormasks[start], &entry->info ) )
322 if( start == SERVERLIST_ORMASKCOUNT || (start > 0 && !serverlist_ormasks[start].active) )
325 if( !serverlist_viewcount ) {
326 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
329 // ok, insert it, we just need to find out where exactly:
332 // check whether to insert it as new first item
333 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[0] ) ) {
334 _ServerList_ViewList_Helper_InsertBefore( 0, entry );
336 } // check whether to insert it as new last item
337 else if( !_ServerList_Entry_Compare( entry, serverlist_viewlist[serverlist_viewcount - 1] ) ) {
338 _ServerList_ViewList_Helper_InsertBefore( serverlist_viewcount, entry );
342 end = serverlist_viewcount - 1;
343 while( end > start + 1 )
345 mid = (start + end) / 2;
346 // test the item that lies in the middle between start and end
347 if( _ServerList_Entry_Compare( entry, serverlist_viewlist[mid] ) )
348 // the item has to be in the upper half
351 // the item has to be in the lower half
354 _ServerList_ViewList_Helper_InsertBefore( start + 1, entry );
357 static void ServerList_ViewList_Remove( serverlist_entry_t *entry )
360 for( i = 0; i < serverlist_viewcount; i++ )
362 if (serverlist_viewlist[i] == entry)
364 _ServerList_ViewList_Helper_Remove(i);
370 void ServerList_RebuildViewList(void)
374 serverlist_viewcount = 0;
375 for( i = 0 ; i < serverlist_cachecount ; i++ )
376 if( serverlist_cache[i].query == SQS_QUERIED )
377 ServerList_ViewList_Insert( &serverlist_cache[i] );
380 void ServerList_ResetMasks(void)
382 memset( &serverlist_andmasks, 0, sizeof( serverlist_andmasks ) );
383 memset( &serverlist_ormasks, 0, sizeof( serverlist_ormasks ) );
387 static void _ServerList_Test(void)
390 for( i = 0 ; i < 1024 ; i++ ) {
391 memset( &serverlist_cache[serverlist_cachecount], 0, sizeof( serverlist_entry_t ) );
392 serverlist_cache[serverlist_cachecount].info.ping = 1000 + 1024 - i;
393 dpsnprintf( serverlist_cache[serverlist_cachecount].info.name, sizeof(serverlist_cache[serverlist_cachecount].info.name), "Black's ServerList Test %i", i );
394 serverlist_cache[serverlist_cachecount].finished = true;
395 sprintf( serverlist_cache[serverlist_cachecount].line1, "%i %s", serverlist_cache[serverlist_cachecount].info.ping, serverlist_cache[serverlist_cachecount].info.name );
396 ServerList_ViewList_Insert( &serverlist_cache[serverlist_cachecount] );
397 serverlist_cachecount++;
402 void ServerList_QueryList(qboolean querydp, qboolean queryqw)
404 //masterquerytime = realtime;
405 masterquerytime = Sys_DoubleTime();
406 masterquerycount = 0;
407 masterreplycount = 0;
408 serverquerycount = 0;
409 serverreplycount = 0;
410 serverlist_cachecount = 0;
411 serverlist_viewcount = 0;
412 serverlist_consoleoutput = false;
414 //_ServerList_Test();
416 NetConn_QueryMasters(querydp, queryqw);
421 int NetConn_Read(lhnetsocket_t *mysocket, void *data, int maxlength, lhnetaddress_t *peeraddress)
423 int length = LHNET_Read(mysocket, data, maxlength, peeraddress);
427 if (cl_netpacketloss.integer)
428 for (i = 0;i < cl_numsockets;i++)
429 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
431 if (developer_networking.integer)
433 char addressstring[128], addressstring2[128];
434 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
437 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
438 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i from %s:\n", mysocket, addressstring, data, maxlength, peeraddress, length, addressstring2);
439 Com_HexDumpToConsole((unsigned char *)data, length);
442 Con_Printf("LHNET_Read(%p (%s), %p, %i, %p) = %i\n", mysocket, addressstring, data, maxlength, peeraddress, length);
447 int NetConn_Write(lhnetsocket_t *mysocket, const void *data, int length, const lhnetaddress_t *peeraddress)
451 if (cl_netpacketloss.integer)
452 for (i = 0;i < cl_numsockets;i++)
453 if (cl_sockets[i] == mysocket && (rand() % 100) < cl_netpacketloss.integer)
455 ret = LHNET_Write(mysocket, data, length, peeraddress);
456 if (developer_networking.integer)
458 char addressstring[128], addressstring2[128];
459 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), addressstring, sizeof(addressstring), true);
460 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
461 Con_Printf("LHNET_Write(%p (%s), %p, %i, %p (%s)) = %i%s\n", mysocket, addressstring, data, length, peeraddress, addressstring2, length, ret == length ? "" : " (ERROR)");
462 Com_HexDumpToConsole((unsigned char *)data, length);
467 int NetConn_WriteString(lhnetsocket_t *mysocket, const char *string, const lhnetaddress_t *peeraddress)
469 // note this does not include the trailing NULL because we add that in the parser
470 return NetConn_Write(mysocket, string, (int)strlen(string), peeraddress);
473 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol)
475 if (protocol == PROTOCOL_QUAKEWORLD)
478 qboolean sendreliable;
480 // note that it is ok to send empty messages to the qw server,
481 // otherwise it won't respond to us at all
483 sendreliable = false;
484 // if the remote side dropped the last reliable message, resend it
485 if (conn->qw.incoming_acknowledged > conn->qw.last_reliable_sequence && conn->qw.incoming_reliable_acknowledged != conn->qw.reliable_sequence)
487 // if the reliable transmit buffer is empty, copy the current message out
488 if (!conn->sendMessageLength && conn->message.cursize)
490 memcpy (conn->sendMessage, conn->message.data, conn->message.cursize);
491 conn->sendMessageLength = conn->message.cursize;
492 SZ_Clear(&conn->message); // clear the message buffer
493 conn->qw.reliable_sequence ^= 1;
496 // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
497 *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->qw.outgoing_sequence | ((unsigned int)sendreliable<<31));
498 // last received unreliable packet number, and last received reliable packet number (0 or 1)
499 *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
501 conn->qw.outgoing_sequence++;
502 // client sends qport in every packet
503 if (conn == cls.netcon)
505 *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport);
507 // also update cls.qw_outgoing_sequence
508 cls.qw_outgoing_sequence = conn->qw.outgoing_sequence;
510 if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400)
512 Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize);
515 // add the reliable message if there is one
518 memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength);
519 packetLen += conn->sendMessageLength;
520 conn->qw.last_reliable_sequence = conn->qw.outgoing_sequence;
522 // add the unreliable message if possible
523 if (packetLen + data->cursize <= 1400)
525 memcpy(sendbuffer + packetLen, data->data, data->cursize);
526 packetLen += data->cursize;
529 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
532 unreliableMessagesSent++;
534 // delay later packets to obey rate limit
535 conn->qw.cleartime = max(conn->qw.cleartime, realtime) + packetLen * conn->qw.rate;
541 unsigned int packetLen;
542 unsigned int dataLen;
544 unsigned int *header;
546 // if a reliable message fragment has been lost, send it again
547 if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
549 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
551 dataLen = conn->sendMessageLength;
556 dataLen = MAX_PACKETFRAGMENT;
560 packetLen = NET_HEADERSIZE + dataLen;
562 header = (unsigned int *)sendbuffer;
563 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
564 header[1] = BigLong(conn->nq.sendSequence - 1);
565 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
567 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
569 conn->lastSendTime = realtime;
574 // if we have a new reliable message to send, do so
575 if (!conn->sendMessageLength && conn->message.cursize)
577 if (conn->message.cursize > (int)sizeof(conn->sendMessage))
579 Con_Printf("NetConn_SendUnreliableMessage: reliable message too big (%u > %u)\n", conn->message.cursize, sizeof(conn->sendMessage));
580 conn->message.overflowed = true;
584 if (developer_networking.integer && conn == cls.netcon)
586 Con_Print("client sending reliable message to server:\n");
587 SZ_HexDumpToConsole(&conn->message);
590 memcpy(conn->sendMessage, conn->message.data, conn->message.cursize);
591 conn->sendMessageLength = conn->message.cursize;
592 SZ_Clear(&conn->message);
594 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
596 dataLen = conn->sendMessageLength;
601 dataLen = MAX_PACKETFRAGMENT;
605 packetLen = NET_HEADERSIZE + dataLen;
607 header = (unsigned int *)sendbuffer;
608 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
609 header[1] = BigLong(conn->nq.sendSequence);
610 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
612 conn->nq.sendSequence++;
614 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
616 conn->lastSendTime = realtime;
618 reliableMessagesSent++;
621 // if we have an unreliable message to send, do so
624 packetLen = NET_HEADERSIZE + data->cursize;
626 if (packetLen > (int)sizeof(sendbuffer))
628 Con_Printf("NetConn_SendUnreliableMessage: message too big %u\n", data->cursize);
632 header = (unsigned int *)sendbuffer;
633 header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
634 header[1] = BigLong(conn->nq.unreliableSendSequence);
635 memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
637 conn->nq.unreliableSendSequence++;
639 NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress);
642 unreliableMessagesSent++;
648 void NetConn_CloseClientPorts(void)
650 for (;cl_numsockets > 0;cl_numsockets--)
651 if (cl_sockets[cl_numsockets - 1])
652 LHNET_CloseSocket(cl_sockets[cl_numsockets - 1]);
655 void NetConn_OpenClientPort(const char *addressstring, int defaultport)
657 lhnetaddress_t address;
659 char addressstring2[1024];
660 if (LHNETADDRESS_FromString(&address, addressstring, defaultport))
662 if ((s = LHNET_OpenSocket_Connectionless(&address)))
664 cl_sockets[cl_numsockets++] = s;
665 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
666 Con_Printf("Client opened a socket on address %s\n", addressstring2);
670 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
671 Con_Printf("Client failed to open a socket on address %s\n", addressstring2);
675 Con_Printf("Client unable to parse address %s\n", addressstring);
678 void NetConn_OpenClientPorts(void)
681 NetConn_CloseClientPorts();
682 port = bound(0, cl_netport.integer, 65535);
683 if (cl_netport.integer != port)
684 Cvar_SetValueQuick(&cl_netport, port);
685 Con_Printf("Client using port %i\n", port);
686 NetConn_OpenClientPort("local:2", 0);
687 NetConn_OpenClientPort(net_address.string, port);
688 //NetConn_OpenClientPort(net_address_ipv6.string, port);
691 void NetConn_CloseServerPorts(void)
693 for (;sv_numsockets > 0;sv_numsockets--)
694 if (sv_sockets[sv_numsockets - 1])
695 LHNET_CloseSocket(sv_sockets[sv_numsockets - 1]);
698 void NetConn_OpenServerPort(const char *addressstring, int defaultport)
700 lhnetaddress_t address;
703 char addressstring2[1024];
705 for (port = defaultport; port <= defaultport + 100; port++)
707 if (LHNETADDRESS_FromString(&address, addressstring, port))
709 if ((s = LHNET_OpenSocket_Connectionless(&address)))
711 sv_sockets[sv_numsockets++] = s;
712 LHNETADDRESS_ToString(LHNET_AddressFromSocket(s), addressstring2, sizeof(addressstring2), true);
713 Con_Printf("Server listening on address %s\n", addressstring2);
718 LHNETADDRESS_ToString(&address, addressstring2, sizeof(addressstring2), true);
719 Con_Printf("Server failed to open socket on address %s\n", addressstring2);
724 Con_Printf("Server unable to parse address %s\n", addressstring);
725 // if it cant parse one address, it wont be able to parse another for sure
731 void NetConn_OpenServerPorts(int opennetports)
734 NetConn_CloseServerPorts();
735 NetConn_UpdateSockets();
736 port = bound(0, sv_netport.integer, 65535);
739 Con_Printf("Server using port %i\n", port);
740 if (sv_netport.integer != port)
741 Cvar_SetValueQuick(&sv_netport, port);
742 if (cls.state != ca_dedicated)
743 NetConn_OpenServerPort("local:1", 0);
746 NetConn_OpenServerPort(net_address.string, port);
747 //NetConn_OpenServerPort(net_address_ipv6.string, port);
749 if (sv_numsockets == 0)
750 Host_Error("NetConn_OpenServerPorts: unable to open any ports!");
753 lhnetsocket_t *NetConn_ChooseClientSocketForAddress(lhnetaddress_t *address)
755 int i, a = LHNETADDRESS_GetAddressType(address);
756 for (i = 0;i < cl_numsockets;i++)
757 if (cl_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])) == a)
758 return cl_sockets[i];
762 lhnetsocket_t *NetConn_ChooseServerSocketForAddress(lhnetaddress_t *address)
764 int i, a = LHNETADDRESS_GetAddressType(address);
765 for (i = 0;i < sv_numsockets;i++)
766 if (sv_sockets[i] && LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(sv_sockets[i])) == a)
767 return sv_sockets[i];
771 netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress)
774 conn = (netconn_t *)Mem_Alloc(netconn_mempool, sizeof(*conn));
775 conn->mysocket = mysocket;
776 conn->peeraddress = *peeraddress;
777 conn->lastMessageTime = realtime;
778 conn->message.data = conn->messagedata;
779 conn->message.maxsize = sizeof(conn->messagedata);
780 conn->message.cursize = 0;
781 // LordHavoc: (inspired by ProQuake) use a short connect timeout to
782 // reduce effectiveness of connection request floods
783 conn->timeout = realtime + net_connecttimeout.value;
784 LHNETADDRESS_ToString(&conn->peeraddress, conn->address, sizeof(conn->address), true);
785 conn->next = netconn_list;
790 void NetConn_Close(netconn_t *conn)
793 // remove connection from list
794 if (conn == netconn_list)
795 netconn_list = conn->next;
798 for (c = netconn_list;c;c = c->next)
802 c->next = conn->next;
806 // not found in list, we'll avoid crashing here...
814 static int clientport = -1;
815 static int clientport2 = -1;
816 static int hostport = -1;
817 void NetConn_UpdateSockets(void)
819 if (cls.state != ca_dedicated)
821 if (clientport2 != cl_netport.integer)
823 clientport2 = cl_netport.integer;
824 if (cls.state == ca_connected)
825 Con_Print("Changing \"cl_port\" will not take effect until you reconnect.\n");
827 if (cls.state == ca_disconnected && clientport != clientport2)
829 clientport = clientport2;
830 NetConn_CloseClientPorts();
832 if (cl_numsockets == 0)
833 NetConn_OpenClientPorts();
836 if (hostport != sv_netport.integer)
838 hostport = sv_netport.integer;
840 Con_Print("Changing \"port\" will not take effect until \"map\" command is executed.\n");
844 static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol)
849 // TODO: add netgraph stuff rather than just packetloss counting...
851 if (protocol == PROTOCOL_QUAKEWORLD)
853 int sequence, sequence_ack;
854 int reliable_ack, reliable_message;
858 sequence = LittleLong(*((int *)(data + 0)));
859 sequence_ack = LittleLong(*((int *)(data + 4)));
863 if (conn != cls.netcon)
868 // 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?)
869 qport = LittleShort(*((int *)(data + 8)));
875 reliable_message = (sequence >> 31) & 1;
876 reliable_ack = (sequence_ack >> 31) & 1;
877 sequence &= ~(1<<31);
878 sequence_ack &= ~(1<<31);
879 if (sequence <= conn->qw.incoming_sequence)
881 //Con_DPrint("Got a stale datagram\n");
884 count = sequence - (conn->qw.incoming_sequence + 1);
887 droppedDatagrams += count;
888 //Con_DPrintf("Dropped %u datagram(s)\n", count);
891 conn->packetlost[conn->packetlostcounter] = true;
892 conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
895 conn->packetlost[conn->packetlostcounter] = false;
896 conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
897 if (reliable_ack == conn->qw.reliable_sequence)
899 // received, now we will be able to send another reliable message
900 conn->sendMessageLength = 0;
901 reliableMessagesReceived++;
903 conn->qw.incoming_sequence = sequence;
904 if (conn == cls.netcon)
905 cls.qw_incoming_sequence = conn->qw.incoming_sequence;
906 conn->qw.incoming_acknowledged = sequence_ack;
907 conn->qw.incoming_reliable_acknowledged = reliable_ack;
908 if (reliable_message)
909 conn->qw.incoming_reliable_sequence ^= 1;
910 conn->lastMessageTime = realtime;
911 conn->timeout = realtime + net_messagetimeout.value;
912 unreliableMessagesReceived++;
913 SZ_Clear(&net_message);
914 SZ_Write(&net_message, data, length);
922 unsigned int sequence;
925 qlength = (unsigned int)BigLong(((int *)data)[0]);
926 flags = qlength & ~NETFLAG_LENGTH_MASK;
927 qlength &= NETFLAG_LENGTH_MASK;
928 // control packets were already handled
929 if (!(flags & NETFLAG_CTL) && qlength == length)
931 sequence = BigLong(((int *)data)[1]);
935 if (flags & NETFLAG_UNRELIABLE)
937 if (sequence >= conn->nq.unreliableReceiveSequence)
939 if (sequence > conn->nq.unreliableReceiveSequence)
941 count = sequence - conn->nq.unreliableReceiveSequence;
942 droppedDatagrams += count;
943 //Con_DPrintf("Dropped %u datagram(s)\n", count);
946 conn->packetlost[conn->packetlostcounter] = true;
947 conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
950 conn->packetlost[conn->packetlostcounter] = false;
951 conn->packetlostcounter = (conn->packetlostcounter + 1) % 100;
952 conn->nq.unreliableReceiveSequence = sequence + 1;
953 conn->lastMessageTime = realtime;
954 conn->timeout = realtime + net_messagetimeout.value;
955 unreliableMessagesReceived++;
958 SZ_Clear(&net_message);
959 SZ_Write(&net_message, data, length);
965 // Con_DPrint("Got a stale datagram\n");
968 else if (flags & NETFLAG_ACK)
970 if (sequence == (conn->nq.sendSequence - 1))
972 if (sequence == conn->nq.ackSequence)
974 conn->nq.ackSequence++;
975 if (conn->nq.ackSequence != conn->nq.sendSequence)
976 Con_DPrint("ack sequencing error\n");
977 conn->lastMessageTime = realtime;
978 conn->timeout = realtime + net_messagetimeout.value;
979 if (conn->sendMessageLength > MAX_PACKETFRAGMENT)
981 unsigned int packetLen;
982 unsigned int dataLen;
984 unsigned int *header;
986 conn->sendMessageLength -= MAX_PACKETFRAGMENT;
987 memcpy(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
989 if (conn->sendMessageLength <= MAX_PACKETFRAGMENT)
991 dataLen = conn->sendMessageLength;
996 dataLen = MAX_PACKETFRAGMENT;
1000 packetLen = NET_HEADERSIZE + dataLen;
1002 header = (unsigned int *)sendbuffer;
1003 header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
1004 header[1] = BigLong(conn->nq.sendSequence);
1005 memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
1007 conn->nq.sendSequence++;
1009 if (NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress) == (int)packetLen)
1011 conn->lastSendTime = realtime;
1016 conn->sendMessageLength = 0;
1019 // Con_DPrint("Duplicate ACK received\n");
1022 // Con_DPrint("Stale ACK received\n");
1025 else if (flags & NETFLAG_DATA)
1027 unsigned int temppacket[2];
1028 temppacket[0] = BigLong(8 | NETFLAG_ACK);
1029 temppacket[1] = BigLong(sequence);
1030 NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
1031 if (sequence == conn->nq.receiveSequence)
1033 conn->lastMessageTime = realtime;
1034 conn->timeout = realtime + net_messagetimeout.value;
1035 conn->nq.receiveSequence++;
1036 if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) {
1037 memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length);
1038 conn->receiveMessageLength += length;
1040 Con_Printf( "Reliable message (seq: %i) too big for message buffer!\n"
1041 "Dropping the message!\n", sequence );
1042 conn->receiveMessageLength = 0;
1045 if (flags & NETFLAG_EOM)
1047 reliableMessagesReceived++;
1048 length = conn->receiveMessageLength;
1049 conn->receiveMessageLength = 0;
1052 SZ_Clear(&net_message);
1053 SZ_Write(&net_message, conn->receiveMessage, length);
1060 receivedDuplicateCount++;
1068 void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress, protocolversion_t initialprotocol)
1070 cls.connect_trying = false;
1071 M_Update_Return_Reason("");
1072 // the connection request succeeded, stop current connection and set up a new connection
1074 // if we're connecting to a remote server, shut down any local server
1075 if (LHNETADDRESS_GetAddressType(peeraddress) != LHNETADDRESSTYPE_LOOP && sv.active)
1076 Host_ShutdownServer ();
1077 // allocate a net connection to keep track of things
1078 cls.netcon = NetConn_Open(mysocket, peeraddress);
1079 Con_Printf("Connection accepted to %s\n", cls.netcon->address);
1080 key_dest = key_game;
1082 cls.demonum = -1; // not in the demo loop now
1083 cls.state = ca_connected;
1084 cls.signon = 0; // need all the signon messages before playing
1085 cls.protocol = initialprotocol;
1086 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1087 Cmd_ForwardStringToServer("new");
1090 int NetConn_IsLocalGame(void)
1092 if (cls.state == ca_connected && sv.active && cl.maxclients == 1)
1097 static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring)
1101 // search the cache for this server and update it
1102 for (n = 0;n < serverlist_cachecount;n++)
1103 if (!strcmp(addressstring, serverlist_cache[n].info.cname))
1105 if (n == serverlist_cachecount)
1107 // LAN search doesnt require an answer from the master server so we wont
1108 // know the ping nor will it be initialized already...
1111 if (serverlist_cachecount == SERVERLIST_TOTALSIZE)
1114 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1115 // store the data the engine cares about (address and ping)
1116 strlcpy(serverlist_cache[serverlist_cachecount].info.cname, addressstring, sizeof(serverlist_cache[serverlist_cachecount].info.cname));
1117 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1118 //serverlist_cache[serverlist_cachecount].querytime = realtime;
1119 serverlist_cache[serverlist_cachecount].querytime = Sys_DoubleTime();
1120 // if not in the slist menu we should print the server to console
1121 if (serverlist_consoleoutput)
1122 Con_Printf("querying %s\n", addressstring);
1123 ++serverlist_cachecount;
1125 // if this is the first reply from this server, count it as having replied
1126 if (serverlist_cache[n].info.ping == 100000)
1128 pingtime = (int)((Sys_DoubleTime() - serverlist_cache[n].querytime) * 1000.0 + 0.5);
1129 pingtime = bound(0, pingtime, 9999);
1131 serverlist_cache[n].info.ping = min(serverlist_cache[n].info.ping, pingtime);
1132 // other server info is updated by the caller
1136 static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n)
1138 serverlist_info_t *info = &serverlist_cache[n].info;
1139 // update description strings for engine menu and console output
1140 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->numplayers > 0 && info->numplayers < info->maxplayers) ? (info->numplayers >= 4 ? '7' : '3') : '1'), info->numplayers, info->maxplayers, info->name);
1141 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);
1142 if (serverlist_cache[n].query == SQS_QUERIED)
1143 ServerList_ViewList_Remove(&serverlist_cache[n]);
1144 // if not in the slist menu we should print the server to console (if wanted)
1145 else if( serverlist_consoleoutput )
1146 Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2);
1147 // and finally, update the view set
1148 ServerList_ViewList_Insert( &serverlist_cache[n] );
1149 serverlist_cache[n].query = SQS_QUERIED;
1152 static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1154 qboolean fromserver;
1155 int ret, c, control;
1157 char *string, addressstring2[128], ipstring[32];
1158 char stringbuf[16384];
1160 // quakeworld ingame packet
1161 fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress);
1163 // convert the address to a string incase we need it
1164 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1166 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1168 // received a command string - strip off the packaging and put it
1169 // into our string buffer with NULL termination
1172 length = min(length, (int)sizeof(stringbuf) - 1);
1173 memcpy(stringbuf, data, length);
1174 stringbuf[length] = 0;
1177 if (developer_networking.integer)
1179 Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2);
1180 Com_HexDumpToConsole(data, length);
1183 if (length > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
1185 // darkplaces or quake3
1186 char protocolnames[1400];
1187 Protocol_Names(protocolnames, sizeof(protocolnames));
1188 Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2);
1189 M_Update_Return_Reason("Got challenge response");
1190 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1191 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1192 // TODO: add userinfo stuff here instead of using NQ commands?
1193 NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress);
1196 if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying)
1198 // darkplaces or quake3
1199 M_Update_Return_Reason("Accepted");
1200 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3);
1203 if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying)
1205 char rejectreason[32];
1206 cls.connect_trying = false;
1208 length = max(length - 7, (int)sizeof(rejectreason) - 1);
1209 memcpy(rejectreason, string, length);
1210 rejectreason[length] = 0;
1211 M_Update_Return_Reason(rejectreason);
1214 if (length >= 13 && !memcmp(string, "infoResponse\x0A", 13))
1216 serverlist_info_t *info;
1220 // search the cache for this server and update it
1221 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1225 info = &serverlist_cache[n].info;
1226 if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0;
1227 if ((s = SearchInfostring(string, "modname" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1228 if ((s = SearchInfostring(string, "mapname" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1229 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1230 if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1;
1231 if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0;
1232 if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1233 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1235 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1239 if (!strncmp(string, "getserversResponse\\", 19) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1241 // Extract the IP addresses
1245 if (serverlist_consoleoutput)
1246 Con_Print("received DarkPlaces server list...\n");
1247 while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0)
1251 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]);
1252 if (serverlist_consoleoutput && developer_networking.integer)
1253 Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring);
1254 // ignore the rest of the message if the serverlist is full
1255 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1257 // also ignore it if we have already queried it (other master server response)
1258 for( n = 0 ; n < serverlist_cachecount ; n++ )
1259 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1261 if( n >= serverlist_cachecount )
1265 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1266 serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_DARKPLACES7;
1267 // store the data the engine cares about (address and ping)
1268 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1269 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1270 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1272 ++serverlist_cachecount;
1275 // move on to next address in packet
1279 // begin or resume serverlist queries
1280 serverlist_querysleep = false;
1281 serverlist_querywaittime = realtime + 3;
1284 if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE)
1286 // Extract the IP addresses
1290 if (serverlist_consoleoutput)
1291 Con_Printf("received QuakeWorld server list from %s...\n", addressstring2);
1292 while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0)
1296 dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]);
1297 if (serverlist_consoleoutput && developer_networking.integer)
1298 Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring);
1299 // ignore the rest of the message if the serverlist is full
1300 if( serverlist_cachecount == SERVERLIST_TOTALSIZE )
1302 // also ignore it if we have already queried it (other master server response)
1303 for( n = 0 ; n < serverlist_cachecount ; n++ )
1304 if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) )
1306 if( n >= serverlist_cachecount )
1310 memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount]));
1311 serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_QUAKEWORLD;
1312 // store the data the engine cares about (address and ping)
1313 strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname));
1314 serverlist_cache[serverlist_cachecount].info.ping = 100000;
1315 serverlist_cache[serverlist_cachecount].query = SQS_QUERYING;
1317 ++serverlist_cachecount;
1320 // move on to next address in packet
1324 // begin or resume serverlist queries
1325 serverlist_querysleep = false;
1326 serverlist_querywaittime = realtime + 3;
1329 if (!strncmp(string, "ping", 4))
1331 if (developer.integer >= 10)
1332 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1333 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1336 if (!strncmp(string, "ack", 3))
1338 // QuakeWorld compatibility
1339 if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying)
1341 // challenge message
1342 Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2);
1343 M_Update_Return_Reason("Got QuakeWorld challenge response");
1344 cls.qw_qport = qport.integer;
1345 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1346 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1347 NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress);
1350 if (length >= 1 && string[0] == 'j' && cls.connect_trying)
1353 M_Update_Return_Reason("QuakeWorld Accepted");
1354 NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD);
1357 if (length > 2 && !memcmp(string, "n\\", 2))
1359 serverlist_info_t *info;
1363 if (serverlist_consoleoutput && developer_networking.integer >= 2)
1364 Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1);
1367 // search the cache for this server and update it
1368 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1372 info = &serverlist_cache[n].info;
1373 strlcpy(info->game, "QuakeWorld", sizeof(info->game));;
1374 if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0;
1375 if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0;
1376 if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0;
1378 info->numplayers = 0; // updated below
1379 if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0;
1380 if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0;
1382 // count active players on server
1383 // (we could gather more info, but we're just after the number)
1384 s = strchr(string, '\n');
1388 while (s < string + length)
1390 for (;s < string + length && *s != '\n';s++)
1392 if (s >= string + length)
1399 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1403 if (string[0] == 'n')
1406 Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1);
1408 // we may not have liked the packet, but it was a command packet, so
1409 // we're done processing this packet now
1412 // quakeworld ingame packet
1413 if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2)
1416 CL_ParseServerMessage();
1419 // netquake control packets, supported for compatibility only
1420 if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
1423 serverlist_info_t *info;
1431 if (developer.integer >= 10)
1432 Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2);
1433 if (cls.connect_trying)
1435 lhnetaddress_t clientportaddress;
1436 clientportaddress = *peeraddress;
1439 unsigned int port = (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
1442 LHNETADDRESS_SetPort(&clientportaddress, port);
1444 M_Update_Return_Reason("Accepted");
1445 // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command)
1446 InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2);
1447 NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE);
1451 if (developer.integer >= 10)
1452 Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2);
1453 cls.connect_trying = false;
1454 M_Update_Return_Reason((char *)data);
1456 // TODO: fix this code so that lan searches for quake servers will work
1457 case CCREP_SERVER_INFO:
1458 if (developer.integer >= 10)
1459 Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2);
1460 // LordHavoc: because the quake server may report weird addresses
1461 // we just ignore it and keep the real address
1463 // search the cache for this server and update it
1464 n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2);
1468 info = &serverlist_cache[n].info;
1469 strlcpy(info->game, "Quake", sizeof(info->game));
1470 strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified
1471 strlcpy(info->name, MSG_ReadString(), sizeof(info->name));
1472 strlcpy(info->map , MSG_ReadString(), sizeof(info->map));
1473 info->numplayers = MSG_ReadByte();
1474 info->maxplayers = MSG_ReadByte();
1475 info->protocol = MSG_ReadByte();
1477 NetConn_ClientParsePacket_ServerList_UpdateCache(n);
1480 case CCREP_PLAYER_INFO:
1481 // we got a CCREP_PLAYER_INFO??
1482 //if (developer.integer >= 10)
1483 Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2);
1485 case CCREP_RULE_INFO:
1486 // we got a CCREP_RULE_INFO??
1487 //if (developer.integer >= 10)
1488 Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2);
1493 // we may not have liked the packet, but it was a valid control
1494 // packet, so we're done processing this packet now
1498 if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2)
1499 CL_ParseServerMessage();
1503 void NetConn_QueryQueueFrame(void)
1509 static double querycounter = 0;
1511 if (serverlist_querysleep)
1514 // apply a cool down time after master server replies,
1515 // to avoid messing up the ping times on the servers
1516 if (serverlist_querywaittime > realtime)
1519 // each time querycounter reaches 1.0 issue a query
1520 querycounter += cl.realframetime * net_slist_queriespersecond.value;
1521 maxqueries = (int)querycounter;
1522 maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer);
1523 querycounter -= maxqueries;
1525 if( maxqueries == 0 ) {
1529 // scan serverlist and issue queries as needed
1530 serverlist_querysleep = true;
1532 timeouttime = realtime - net_slist_timeout.value;
1533 for( index = 0, queries = 0 ; index < serverlist_cachecount && queries < maxqueries ; index++ )
1535 serverlist_entry_t *entry = &serverlist_cache[ index ];
1536 if( entry->query != SQS_QUERYING )
1541 serverlist_querysleep = false;
1542 if( entry->querycounter != 0 && entry->querytime > timeouttime )
1547 if( entry->querycounter != (unsigned) net_slist_maxtries.integer )
1549 lhnetaddress_t address;
1552 LHNETADDRESS_FromString(&address, entry->info.cname, 0);
1553 if (entry->protocol == PROTOCOL_QUAKEWORLD)
1555 for (socket = 0; socket < cl_numsockets ; socket++)
1556 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address);
1560 for (socket = 0; socket < cl_numsockets ; socket++)
1561 NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address);
1564 //entry->querytime = realtime;
1565 entry->querytime = Sys_DoubleTime();
1566 entry->querycounter++;
1568 // if not in the slist menu we should print the server to console
1569 if (serverlist_consoleoutput)
1570 Con_Printf("querying %25s (%i. try)\n", entry->info.cname, entry->querycounter);
1576 entry->query = SQS_TIMEDOUT;
1581 void NetConn_ClientFrame(void)
1584 lhnetaddress_t peeraddress;
1585 NetConn_UpdateSockets();
1586 if (cls.connect_trying && cls.connect_nextsendtime < realtime)
1588 if (cls.connect_remainingtries == 0)
1589 M_Update_Return_Reason("Connect: Waiting 10 seconds for reply");
1590 cls.connect_nextsendtime = realtime + 1;
1591 cls.connect_remainingtries--;
1592 if (cls.connect_remainingtries <= -10)
1594 cls.connect_trying = false;
1595 M_Update_Return_Reason("Connect: Failed");
1598 // try challenge first (newer DP server or QW)
1599 NetConn_WriteString(cls.connect_mysocket, "\377\377\377\377getchallenge", &cls.connect_address);
1600 // then try netquake as a fallback (old server, or netquake)
1601 SZ_Clear(&net_message);
1602 // save space for the header, filled in later
1603 MSG_WriteLong(&net_message, 0);
1604 MSG_WriteByte(&net_message, CCREQ_CONNECT);
1605 MSG_WriteString(&net_message, "QUAKE");
1606 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
1607 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1608 NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
1609 SZ_Clear(&net_message);
1611 for (i = 0;i < cl_numsockets;i++)
1612 while (cl_sockets[i] && (length = NetConn_Read(cl_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
1613 NetConn_ClientParsePacket(cl_sockets[i], readbuffer, length, &peeraddress);
1614 NetConn_QueryQueueFrame();
1615 if (cls.netcon && realtime > cls.netcon->timeout)
1617 Con_Print("Connection timed out\n");
1619 Host_ShutdownServer ();
1623 #define MAX_CHALLENGES 128
1626 lhnetaddress_t address;
1630 challenge[MAX_CHALLENGES];
1632 static void NetConn_BuildChallengeString(char *buffer, int bufferlength)
1636 for (i = 0;i < bufferlength - 1;i++)
1640 c = rand () % (127 - 33) + 33;
1641 } while (c == '\\' || c == ';' || c == '"' || c == '%' || c == '/');
1647 static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg, size_t out_size, qboolean fullstatus)
1649 unsigned int nb_clients = 0, i;
1652 // How many clients are there?
1653 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1654 if (svs.clients[i].active)
1657 // TODO: we should add more information for the full status string
1658 length = dpsnprintf(out_msg, out_size,
1659 "\377\377\377\377%s\x0A"
1660 "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d"
1661 "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d"
1664 fullstatus ? "statusResponse" : "infoResponse",
1665 gamename, com_modname, gameversion.integer, svs.maxclients,
1666 nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION,
1667 challenge ? "\\challenge\\" : "", challenge ? challenge : "",
1668 fullstatus ? "\n" : "");
1670 // Make sure it fits in the buffer
1679 ptr = out_msg + length;
1680 left = (int)out_size - length;
1682 for (i = 0;i < (unsigned int)svs.maxclients;i++)
1684 client_t *cl = &svs.clients[i];
1687 int nameind, cleanind;
1689 char cleanname [sizeof(cl->name)];
1691 // Remove all characters '"' and '\' in the player name
1696 curchar = cl->name[nameind++];
1697 if (curchar != '"' && curchar != '\\')
1699 cleanname[cleanind++] = curchar;
1700 if (cleanind == sizeof(cleanname) - 1)
1703 } while (curchar != '\0');
1705 length = dpsnprintf(ptr, left, "%d %d \"%s\"\n",
1707 (int)(cl->ping * 1000.0f),
1720 extern void SV_SendServerinfo (client_t *client);
1721 static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress)
1723 int i, ret, clientnum, best;
1727 char *s, *string, response[1400], addressstring2[128], stringbuf[16384];
1732 // convert the address to a string incase we need it
1733 LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true);
1735 // see if we can identify the sender as a local player
1736 // (this is necessary for rcon to send a reliable reply if the client is
1737 // actually on the server, not sending remotely)
1738 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
1739 if (host_client->netconnection && host_client->netconnection->mysocket == mysocket && !LHNETADDRESS_Compare(&host_client->netconnection->peeraddress, peeraddress))
1741 if (i == svs.maxclients)
1744 if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255)
1746 // received a command string - strip off the packaging and put it
1747 // into our string buffer with NULL termination
1750 length = min(length, (int)sizeof(stringbuf) - 1);
1751 memcpy(stringbuf, data, length);
1752 stringbuf[length] = 0;
1755 if (developer.integer >= 10)
1757 Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2);
1758 Com_HexDumpToConsole(data, length);
1761 if (length >= 12 && !memcmp(string, "getchallenge", 12))
1763 for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++)
1765 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address))
1767 if (besttime > challenge[i].time)
1768 besttime = challenge[best = i].time;
1770 // if we did not find an exact match, choose the oldest and
1771 // update address and string
1772 if (i == MAX_CHALLENGES)
1775 challenge[i].address = *peeraddress;
1776 NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string));
1778 challenge[i].time = realtime;
1779 // send the challenge
1780 NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress);
1783 if (length > 8 && !memcmp(string, "connect\\", 8))
1787 if ((s = SearchInfostring(string, "challenge")))
1789 // validate the challenge
1790 for (i = 0;i < MAX_CHALLENGES;i++)
1791 if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s))
1793 if (i < MAX_CHALLENGES)
1795 // check engine protocol
1796 if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3"))
1798 if (developer.integer >= 10)
1799 Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2);
1800 NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress);
1804 // see if this is a duplicate connection request
1805 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1806 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1808 if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value)
1810 // client is still trying to connect,
1811 // so we send a duplicate reply
1812 if (developer.integer >= 10)
1813 Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2);
1814 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1817 else if (clientnum < svs.maxclients)
1819 if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
1821 // client crashed and is coming back, keep their stuff intact
1822 SV_SendServerinfo(client);
1823 //host_client = client;
1824 //SV_DropClient (true);
1831 // this is a new client, find a slot
1832 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1833 if (!client->active)
1835 if (clientnum < svs.maxclients)
1837 // prepare the client struct
1838 if ((conn = NetConn_Open(mysocket, peeraddress)))
1840 // allocated connection
1841 if (developer.integer >= 10)
1842 Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address);
1843 NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress);
1844 // now set up the client
1846 SV_ConnectClient(clientnum, conn);
1848 NetConn_Heartbeat(1);
1854 if (developer.integer >= 10)
1855 Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2);
1856 NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress);
1864 if (length >= 7 && !memcmp(string, "getinfo", 7))
1866 const char *challenge = NULL;
1868 // If there was a challenge in the getinfo message
1869 if (length > 8 && string[7] == ' ')
1870 challenge = string + 8;
1872 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false))
1874 if (developer.integer >= 10)
1875 Con_Printf("Sending reply to master %s - %s\n", addressstring2, response);
1876 NetConn_WriteString(mysocket, response, peeraddress);
1880 if (length >= 9 && !memcmp(string, "getstatus", 9))
1882 const char *challenge = NULL;
1884 // If there was a challenge in the getinfo message
1885 if (length > 10 && string[9] == ' ')
1886 challenge = string + 10;
1888 if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true))
1890 if (developer.integer >= 10)
1891 Con_Printf("Sending reply to client %s - %s\n", addressstring2, response);
1892 NetConn_WriteString(mysocket, response, peeraddress);
1896 if (length >= 5 && !memcmp(string, "rcon ", 5))
1899 char *s = string + 5;
1901 for (i = 0;*s > ' ';s++)
1902 if (i < (int)sizeof(password) - 1)
1905 if (password[0] > ' ' && !strcmp(rcon_password.string, password))
1907 // looks like a legitimate rcon command with the correct password
1908 Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s);
1909 rcon_redirect = true;
1910 rcon_redirect_bufferpos = 0;
1911 Cmd_ExecuteString(s, src_command);
1912 rcon_redirect_buffer[rcon_redirect_bufferpos] = 0;
1913 rcon_redirect = false;
1914 // print resulting text to client
1915 // if client is playing, send a reliable reply instead of
1919 // if the netconnection is loop, then this is the
1920 // local player on a listen mode server, and it would
1921 // result in duplicate printing to the console
1922 // (not that the local player should be using rcon
1923 // when they have the console)
1924 if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
1925 SV_ClientPrintf("%s", rcon_redirect_buffer);
1930 dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer);
1931 NetConn_WriteString(mysocket, response, peeraddress);
1936 if (!strncmp(string, "ping", 4))
1938 if (developer.integer >= 10)
1939 Con_Printf("Received ping from %s, sending ack\n", addressstring2);
1940 NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress);
1943 if (!strncmp(string, "ack", 3))
1945 // we may not have liked the packet, but it was a command packet, so
1946 // we're done processing this packet now
1949 // netquake control packets, supported for compatibility only, and only
1950 // when running game protocols that are normally served via this connection
1952 // (this protects more modern protocols against being used for
1953 // Quake packet flood Denial Of Service attacks)
1954 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))
1962 if (developer.integer >= 10)
1963 Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2);
1964 if (length >= (int)strlen("QUAKE") + 1 + 1)
1966 if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION)
1968 if (developer.integer >= 10)
1969 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2);
1970 SZ_Clear(&net_message);
1971 // save space for the header, filled in later
1972 MSG_WriteLong(&net_message, 0);
1973 MSG_WriteByte(&net_message, CCREP_REJECT);
1974 MSG_WriteString(&net_message, "Incompatible version.\n");
1975 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
1976 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
1977 SZ_Clear(&net_message);
1981 // see if this is a duplicate connection request
1982 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
1983 if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0)
1985 if (clientnum < svs.maxclients)
1987 // duplicate connection request
1988 if (realtime - client->connecttime < 2.0)
1990 // client is still trying to connect,
1991 // so we send a duplicate reply
1992 if (developer.integer >= 10)
1993 Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2);
1994 SZ_Clear(&net_message);
1995 // save space for the header, filled in later
1996 MSG_WriteLong(&net_message, 0);
1997 MSG_WriteByte(&net_message, CCREP_ACCEPT);
1998 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
1999 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2000 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2001 SZ_Clear(&net_message);
2004 else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value)
2006 SV_SendServerinfo(client);
2007 // the old client hasn't sent us anything
2008 // in quite a while, so kick off and let
2009 // the retry take care of it...
2010 //host_client = client;
2011 //SV_DropClient (true);
2017 // this is a new client, find a slot
2018 for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++)
2019 if (!client->active)
2021 if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL)
2023 // connect to the client
2024 // everything is allocated, just fill in the details
2025 strlcpy (conn->address, addressstring2, sizeof (conn->address));
2026 if (developer.integer >= 10)
2027 Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2);
2028 // send back the info about the server connection
2029 SZ_Clear(&net_message);
2030 // save space for the header, filled in later
2031 MSG_WriteLong(&net_message, 0);
2032 MSG_WriteByte(&net_message, CCREP_ACCEPT);
2033 MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
2034 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2035 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2036 SZ_Clear(&net_message);
2037 // now set up the client struct
2039 SV_ConnectClient(clientnum, conn);
2041 NetConn_Heartbeat(1);
2045 if (developer.integer >= 10)
2046 Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2);
2047 // no room; try to let player know
2048 SZ_Clear(&net_message);
2049 // save space for the header, filled in later
2050 MSG_WriteLong(&net_message, 0);
2051 MSG_WriteByte(&net_message, CCREP_REJECT);
2052 MSG_WriteString(&net_message, "Server is full.\n");
2053 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2054 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2055 SZ_Clear(&net_message);
2061 case CCREQ_SERVER_INFO:
2062 if (developer.integer >= 10)
2063 Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2);
2064 if (sv.active && !strcmp(MSG_ReadString(), "QUAKE"))
2067 char myaddressstring[128];
2068 if (developer.integer >= 10)
2069 Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2);
2070 SZ_Clear(&net_message);
2071 // save space for the header, filled in later
2072 MSG_WriteLong(&net_message, 0);
2073 MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
2074 LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true);
2075 MSG_WriteString(&net_message, myaddressstring);
2076 MSG_WriteString(&net_message, hostname.string);
2077 MSG_WriteString(&net_message, sv.name);
2078 // How many clients are there?
2079 for (i = 0, numclients = 0;i < svs.maxclients;i++)
2080 if (svs.clients[i].active)
2082 MSG_WriteByte(&net_message, numclients);
2083 MSG_WriteByte(&net_message, svs.maxclients);
2084 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2085 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2086 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2087 SZ_Clear(&net_message);
2090 case CCREQ_PLAYER_INFO:
2091 if (developer.integer >= 10)
2092 Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2);
2095 int playerNumber, activeNumber, clientNumber;
2098 playerNumber = MSG_ReadByte();
2100 for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
2101 if (client->active && ++activeNumber == playerNumber)
2103 if (clientNumber != svs.maxclients)
2105 SZ_Clear(&net_message);
2106 // save space for the header, filled in later
2107 MSG_WriteLong(&net_message, 0);
2108 MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
2109 MSG_WriteByte(&net_message, playerNumber);
2110 MSG_WriteString(&net_message, client->name);
2111 MSG_WriteLong(&net_message, client->colors);
2112 MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags);
2113 MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
2114 MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
2115 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2116 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2117 SZ_Clear(&net_message);
2121 case CCREQ_RULE_INFO:
2122 if (developer.integer >= 10)
2123 Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2);
2129 // find the search start location
2130 prevCvarName = MSG_ReadString();
2131 var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY);
2133 // send the response
2134 SZ_Clear(&net_message);
2135 // save space for the header, filled in later
2136 MSG_WriteLong(&net_message, 0);
2137 MSG_WriteByte(&net_message, CCREP_RULE_INFO);
2140 MSG_WriteString(&net_message, var->name);
2141 MSG_WriteString(&net_message, var->string);
2143 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2144 NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
2145 SZ_Clear(&net_message);
2151 // we may not have liked the packet, but it was a valid control
2152 // packet, so we're done processing this packet now
2157 if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol)) == 2)
2160 SV_ReadClientMessage();
2168 void NetConn_ServerFrame(void)
2171 lhnetaddress_t peeraddress;
2172 for (i = 0;i < sv_numsockets;i++)
2173 while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0)
2174 NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress);
2175 for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
2177 // never timeout loopback connections
2178 if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP)
2180 Con_Printf("Client \"%s\" connection timed out\n", host_client->name);
2182 SV_DropClient(false);
2188 void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
2192 lhnetaddress_t masteraddress;
2193 lhnetaddress_t broadcastaddress;
2196 if (serverlist_cachecount >= SERVERLIST_TOTALSIZE)
2199 // 26000 is the default quake server port, servers on other ports will not
2201 // note this is IPv4-only, I doubt there are IPv6-only LANs out there
2202 LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000);
2206 for (i = 0;i < cl_numsockets;i++)
2210 // search LAN for Quake servers
2211 SZ_Clear(&net_message);
2212 // save space for the header, filled in later
2213 MSG_WriteLong(&net_message, 0);
2214 MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
2215 MSG_WriteString(&net_message, "QUAKE");
2216 MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
2217 *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
2218 NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
2219 SZ_Clear(&net_message);
2221 // search LAN for DarkPlaces servers
2222 NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress);
2224 // build the getservers message to send to the dpmaster master servers
2225 dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION);
2228 for (masternum = 0;sv_masters[masternum].name;masternum++)
2230 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])))
2233 NetConn_WriteString(cl_sockets[i], request, &masteraddress);
2240 // only query QuakeWorld servers when the user wants to
2243 for (i = 0;i < cl_numsockets;i++)
2247 // search LAN for QuakeWorld servers
2248 NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress);
2250 // build the getservers message to send to the qwmaster master servers
2251 // note this has no -1 prefix, and the trailing nul byte is sent
2252 dpsnprintf(request, sizeof(request), "c\n");
2255 for (masternum = 0;sv_qwmasters[masternum].name;masternum++)
2257 if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i])))
2259 if (m_state != m_slist)
2261 char lookupstring[128];
2262 LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true);
2263 Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string);
2266 NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress);
2272 if (!masterquerycount)
2274 Con_Print("Unable to query master servers, no suitable network sockets active.\n");
2275 M_Update_Return_Reason("No network");
2279 void NetConn_Heartbeat(int priority)
2281 lhnetaddress_t masteraddress;
2283 lhnetsocket_t *mysocket;
2285 // if it's a state change (client connected), limit next heartbeat to no
2286 // more than 30 sec in the future
2287 if (priority == 1 && nextheartbeattime > realtime + 30.0)
2288 nextheartbeattime = realtime + 30.0;
2290 // limit heartbeatperiod to 30 to 270 second range,
2291 // lower limit is to avoid abusing master servers with excess traffic,
2292 // upper limit is to avoid timing out on the master server (which uses
2294 if (sv_heartbeatperiod.value < 30)
2295 Cvar_SetValueQuick(&sv_heartbeatperiod, 30);
2296 if (sv_heartbeatperiod.value > 270)
2297 Cvar_SetValueQuick(&sv_heartbeatperiod, 270);
2299 // make advertising optional and don't advertise singleplayer games, and
2300 // only send a heartbeat as often as the admin wants
2301 if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime))
2303 nextheartbeattime = realtime + sv_heartbeatperiod.value;
2304 for (masternum = 0;sv_masters[masternum].name;masternum++)
2305 if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress)))
2306 NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress);
2310 static void Net_Heartbeat_f(void)
2313 NetConn_Heartbeat(2);
2315 Con_Print("No server running, can not heartbeat to master server.\n");
2318 void PrintStats(netconn_t *conn)
2320 if ((cls.state == ca_connected && cls.protocol == PROTOCOL_QUAKEWORLD) || (sv.active && sv.protocol == PROTOCOL_QUAKEWORLD))
2321 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->qw.outgoing_sequence, conn->qw.incoming_sequence);
2323 Con_Printf("address=%21s canSend=%u sendSeq=%6u recvSeq=%6u\n", conn->address, !conn->sendMessageLength, conn->nq.sendSequence, conn->nq.receiveSequence);
2326 void Net_Stats_f(void)
2329 Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent);
2330 Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived);
2331 Con_Printf("reliable messages sent = %i\n", reliableMessagesSent);
2332 Con_Printf("reliable messages received = %i\n", reliableMessagesReceived);
2333 Con_Printf("packetsSent = %i\n", packetsSent);
2334 Con_Printf("packetsReSent = %i\n", packetsReSent);
2335 Con_Printf("packetsReceived = %i\n", packetsReceived);
2336 Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount);
2337 Con_Printf("droppedDatagrams = %i\n", droppedDatagrams);
2338 Con_Print("connections =\n");
2339 for (conn = netconn_list;conn;conn = conn->next)
2343 void Net_Slist_f(void)
2345 ServerList_ResetMasks();
2346 serverlist_sortbyfield = SLIF_PING;
2347 serverlist_sortdescending = false;
2348 if (m_state != m_slist) {
2349 Con_Print("Sending requests to master servers\n");
2350 ServerList_QueryList(true, false);
2351 serverlist_consoleoutput = true;
2352 Con_Print("Listening for replies...\n");
2354 ServerList_QueryList(true, false);
2357 void Net_SlistQW_f(void)
2359 ServerList_ResetMasks();
2360 serverlist_sortbyfield = SLIF_PING;
2361 serverlist_sortdescending = false;
2362 if (m_state != m_slist) {
2363 Con_Print("Sending requests to master servers\n");
2364 ServerList_QueryList(false, true);
2365 serverlist_consoleoutput = true;
2366 Con_Print("Listening for replies...\n");
2368 ServerList_QueryList(false, true);
2371 void NetConn_Init(void)
2374 lhnetaddress_t tempaddress;
2375 netconn_mempool = Mem_AllocPool("network connections", 0, NULL);
2376 Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics");
2377 Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information");
2378 Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information");
2379 Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)");
2380 Cvar_RegisterVariable(&net_slist_queriespersecond);
2381 Cvar_RegisterVariable(&net_slist_queriesperframe);
2382 Cvar_RegisterVariable(&net_slist_timeout);
2383 Cvar_RegisterVariable(&net_slist_maxtries);
2384 Cvar_RegisterVariable(&net_messagetimeout);
2385 Cvar_RegisterVariable(&net_messagerejointimeout);
2386 Cvar_RegisterVariable(&net_connecttimeout);
2387 Cvar_RegisterVariable(&cl_netlocalping);
2388 Cvar_RegisterVariable(&cl_netpacketloss);
2389 Cvar_RegisterVariable(&hostname);
2390 Cvar_RegisterVariable(&developer_networking);
2391 Cvar_RegisterVariable(&cl_netport);
2392 Cvar_RegisterVariable(&sv_netport);
2393 Cvar_RegisterVariable(&net_address);
2394 //Cvar_RegisterVariable(&net_address_ipv6);
2395 Cvar_RegisterVariable(&sv_public);
2396 Cvar_RegisterVariable(&sv_heartbeatperiod);
2397 for (i = 0;sv_masters[i].name;i++)
2398 Cvar_RegisterVariable(&sv_masters[i]);
2399 Cvar_RegisterVariable(&gameversion);
2400 // 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.
2401 if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc)
2403 if (LHNETADDRESS_FromString(&tempaddress, com_argv[i + 1], 0) == 1)
2405 Con_Printf("-ip option used, setting net_address to \"%s\"\n");
2406 Cvar_SetQuick(&net_address, com_argv[i + 1]);
2409 Con_Printf("-ip option used, but unable to parse the address \"%s\"\n", com_argv[i + 1]);
2411 // 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
2412 if (((i = COM_CheckParm("-port")) || (i = COM_CheckParm("-ipport")) || (i = COM_CheckParm("-udpport"))) && i + 1 < com_argc)
2414 i = atoi(com_argv[i + 1]);
2415 if (i >= 0 && i < 65536)
2417 Con_Printf("-port option used, setting port cvar to %i\n", i);
2418 Cvar_SetValueQuick(&sv_netport, i);
2421 Con_Printf("-port option used, but %i is not a valid port number\n", i);
2425 net_message.data = net_message_buf;
2426 net_message.maxsize = sizeof(net_message_buf);
2427 net_message.cursize = 0;
2431 void NetConn_Shutdown(void)
2433 NetConn_CloseClientPorts();
2434 NetConn_CloseServerPorts();