X-Git-Url: http://de.git.xonotic.org/?p=xonotic%2Fdarkplaces.git;a=blobdiff_plain;f=netconn.c;h=02f6b5a9e718ed5492b054e786f9b8ba5a8d3c31;hp=0ce9c74578f261a21574d7c164722ebf669eaaec;hb=ef8b2c81a2d25c92dde622e451787cb1e0dca142;hpb=b84125ed0d5fc6922a9ea18b7762b489e377175d diff --git a/netconn.c b/netconn.c index 0ce9c745..02f6b5a9 100755 --- a/netconn.c +++ b/netconn.c @@ -23,13 +23,13 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" #include "lhnet.h" -#define MASTER_PORT 27950 +#define QWMASTER_PORT 27000 +#define DPMASTER_PORT 27950 // note this defaults on for dedicated servers, off for listen servers -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)"}; +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"}; static cvar_t sv_heartbeatperiod = {CVAR_SAVE, "sv_heartbeatperiod", "120", "how often to send heartbeat in seconds (only used if sv_public is 1)"}; -// FIXME: resolve DNS on masters whenever their value changes and cache it (to avoid major delays in active servers when they heartbeat) static cvar_t sv_masters [] = { {CVAR_SAVE, "sv_master1", "", "user-chosen master server 1"}, @@ -43,14 +43,36 @@ static cvar_t sv_masters [] = {0, NULL, NULL, NULL} }; +static cvar_t sv_qwmasters [] = +{ + {CVAR_SAVE, "sv_qwmaster1", "", "user-chosen qwmaster server 1"}, + {CVAR_SAVE, "sv_qwmaster2", "", "user-chosen qwmaster server 2"}, + {CVAR_SAVE, "sv_qwmaster3", "", "user-chosen qwmaster server 3"}, + {CVAR_SAVE, "sv_qwmaster4", "", "user-chosen qwmaster server 4"}, + {0, "sv_qwmasterextra1", "192.246.40.37:27000", "id Limbo (admin: id Software)"}, + {0, "sv_qwmasterextra2", "192.246.40.37:27002", "id CTF (admin: id Software)"}, + {0, "sv_qwmasterextra3", "192.246.40.37:27003", "id TeamFortress (admin: id Software)"}, + {0, "sv_qwmasterextra4", "192.246.40.37:27004", "id Miscilaneous (admin: id Software)"}, + {0, "sv_qwmasterextra5", "192.246.40.37:27006", "id Deathmatch Only (admin: id Software)"}, + {0, "sv_qwmasterextra6", "150.254.66.120:27000", "Poland's master server. (admin: unknown)"}, + {0, "sv_qwmasterextra7", "62.112.145.129:27000", "Ocrana master server. (admin: unknown)"}, + {0, "sv_qwmasterextra8", "master.edome.net", "edome master server. (admin: unknown)"}, + {0, "sv_qwmasterextra9", "qwmaster.barrysworld.com", "barrysworld master server. (admin: unknown)"}, + {0, "sv_qwmasterextra10", "qwmaster.ocrana.de:27000", "Ocrana2 master server. (admin: unknown)"}, + {0, "sv_qwmasterextra11", "213.221.174.165:27000", "unknown1 master server. (admin: unknown)"}, + {0, "sv_qwmasterextra12", "195.74.0.8", "unknown2 master server. (admin: unknown)"}, + {0, "sv_qwmasterextra13", "204.182.161.2", "unknown3 master server. (admin: unknown)"}, + {0, NULL, NULL, NULL} +}; + static double nextheartbeattime = 0; sizebuf_t net_message; static unsigned char net_message_buf[NET_MAXMESSAGE]; cvar_t net_messagetimeout = {0, "net_messagetimeout","300", "drops players who have not sent any packets for this many seconds"}; -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)"}; 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)"}; +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)"}; cvar_t hostname = {CVAR_SAVE, "hostname", "UNNAMED", "server message to show in server browser"}; cvar_t developer_networking = {0, "developer_networking", "0", "prints all received and sent packets (recommended only for debugging)"}; @@ -61,6 +83,8 @@ static cvar_t net_slist_queriesperframe = {0, "net_slist_queriesperframe", "4", static cvar_t net_slist_timeout = {0, "net_slist_timeout", "4", "how long to listen for a server information response before giving up"}; 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)"}; +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"}; + /* statistic counters */ static int packetsSent = 0; static int packetsReSent = 0; @@ -80,15 +104,19 @@ int serverquerycount = 0; int serverreplycount = 0; // this is only false if there are still servers left to query -int serverlist_querysleep = true; +static qboolean serverlist_querysleep = true; +// this is pushed a second or two ahead of realtime whenever a master server +// reply is received, to avoid issuing queries while master replies are still +// flooding in (which would make a mess of the ping times) +static double serverlist_querywaittime = 0; static unsigned char sendbuffer[NET_HEADERSIZE+NET_MAXMESSAGE]; static unsigned char readbuffer[NET_HEADERSIZE+NET_MAXMESSAGE]; -int cl_numsockets; -lhnetsocket_t *cl_sockets[16]; -int sv_numsockets; -lhnetsocket_t *sv_sockets[16]; +static int cl_numsockets; +static lhnetsocket_t *cl_sockets[16]; +static int sv_numsockets; +static lhnetsocket_t *sv_sockets[16]; netconn_t *netconn_list = NULL; mempool_t *netconn_mempool = NULL; @@ -98,6 +126,10 @@ cvar_t sv_netport = {0, "port", "26000", "server port for players to connect to" cvar_t net_address = {0, "net_address", "0.0.0.0", "network address to open ports on"}; //cvar_t net_netaddress_ipv6 = {0, "net_address_ipv6", "[0:0:0:0:0:0:0:0]", "network address to open ipv6 ports on"}; +char net_extresponse[NET_EXTRESPONSE_MAX][1400]; +int net_extresponse_count = 0; +int net_extresponse_last = 0; + // ServerList interface serverlist_mask_t serverlist_andmasks[SERVERLIST_ANDMASKCOUNT]; serverlist_mask_t serverlist_ormasks[SERVERLIST_ORMASKCOUNT]; @@ -178,7 +210,12 @@ static qboolean _ServerList_Entry_Compare( serverlist_entry_t *A, serverlist_ent if( serverlist_sortdescending ) return result > 0; - return result < 0; + if (result != 0) + return result < 0; + // if the chosen sort key is identical, sort by index + // (makes this a stable sort, so that later replies from servers won't + // shuffle the servers around when they have the same ping) + return A < B; } static qboolean _ServerList_CompareInt( int A, serverlist_maskop_t op, int B ) @@ -273,6 +310,10 @@ static void ServerList_ViewList_Insert( serverlist_entry_t *entry ) { int start, end, mid; + // reject incompatible servers + if (entry->info.gameversion != gameversion.integer) + return; + // FIXME: change this to be more readable (...) // now check whether it passes through the masks for( start = 0 ; serverlist_andmasks[start].active && start < SERVERLIST_ANDMASKCOUNT ; start++ ) @@ -362,9 +403,10 @@ static void _ServerList_Test(void) } #endif -void ServerList_QueryList(void) +void ServerList_QueryList(qboolean querydp, qboolean queryqw) { - masterquerytime = realtime; + //masterquerytime = realtime; + masterquerytime = Sys_DoubleTime(); masterquerycount = 0; masterreplycount = 0; serverquerycount = 0; @@ -375,7 +417,7 @@ void ServerList_QueryList(void) //_ServerList_Test(); - NetConn_QueryMasters(); + NetConn_QueryMasters(querydp, queryqw); } // rest @@ -439,11 +481,8 @@ int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolvers int packetLen; qboolean sendreliable; - if (data->cursize == 0 && conn->message.cursize == 0) - { - Con_Printf ("Datagram_SendUnreliableMessage: zero length message\n"); - return -1; - } + // note that it is ok to send empty messages to the qw server, + // otherwise it won't respond to us at all sendreliable = false; // if the remote side dropped the last reliable message, resend it @@ -459,34 +498,46 @@ int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolvers sendreliable = true; } // outgoing unreliable packet number, and outgoing reliable packet number (0 or 1) - *((int *)(sendbuffer + 0)) = LittleLong(conn->qw.outgoing_sequence | (sendreliable<<31)); + *((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->qw.outgoing_sequence | ((unsigned int)sendreliable<<31)); // last received unreliable packet number, and last received reliable packet number (0 or 1) - *((int *)(sendbuffer + 4)) = LittleLong(conn->qw.incoming_sequence | (conn->qw.incoming_reliable_sequence<<31)); + *((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31)); packetLen = 8; + conn->qw.outgoing_sequence++; // client sends qport in every packet if (conn == cls.netcon) { - *((short *)(sendbuffer + 8)) = LittleShort(cls.qport); + *((short *)(sendbuffer + 8)) = LittleShort(cls.qw_qport); packetLen += 2; + // also update cls.qw_outgoing_sequence + cls.qw_outgoing_sequence = conn->qw.outgoing_sequence; } - if (packetLen + (sendreliable ? conn->sendMessageLength : 0) + data->cursize > (int)sizeof(sendbuffer)) + if (packetLen + (sendreliable ? conn->sendMessageLength : 0) > 1400) { Con_Printf ("NetConn_SendUnreliableMessage: reliable message too big %u\n", data->cursize); return -1; } + // add the reliable message if there is one if (sendreliable) { memcpy(sendbuffer + packetLen, conn->sendMessage, conn->sendMessageLength); packetLen += conn->sendMessageLength; + conn->qw.last_reliable_sequence = conn->qw.outgoing_sequence; + } + // add the unreliable message if possible + if (packetLen + data->cursize <= 1400) + { + memcpy(sendbuffer + packetLen, data->data, data->cursize); + packetLen += data->cursize; } - memcpy(sendbuffer + packetLen, data->data, data->cursize); - packetLen += data->cursize; - conn->qw.outgoing_sequence++; NetConn_Write(conn->mysocket, (void *)&sendbuffer, packetLen, &conn->peeraddress); packetsSent++; unreliableMessagesSent++; + + // delay later packets to obey rate limit + conn->qw.cleartime = max(conn->qw.cleartime, realtime) + packetLen * conn->qw.rate; + return 0; } else @@ -740,10 +791,15 @@ netconn_t *NetConn_Open(lhnetsocket_t *mysocket, lhnetaddress_t *peeraddress) return conn; } +void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress); void NetConn_Close(netconn_t *conn) { netconn_t *c; // remove connection from list + + // allow the client to reconnect immediately + NetConn_ClearConnectFlood(&(conn->peeraddress)); + if (conn == netconn_list) netconn_list = conn->next; else @@ -794,11 +850,13 @@ void NetConn_UpdateSockets(void) } } -static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol) +static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int length, protocolversion_t protocol, double newtimeout) { if (length < 8) return 0; + // TODO: add netgraph stuff rather than just packetloss counting... + if (protocol == PROTOCOL_QUAKEWORLD) { int sequence, sequence_ack; @@ -823,21 +881,28 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len } packetsReceived++; - reliable_message = sequence >> 31; - reliable_ack = sequence_ack >> 31; + reliable_message = (sequence >> 31) & 1; + reliable_ack = (sequence_ack >> 31) & 1; sequence &= ~(1<<31); sequence_ack &= ~(1<<31); if (sequence <= conn->qw.incoming_sequence) { - Con_DPrint("Got a stale datagram\n"); + //Con_DPrint("Got a stale datagram\n"); return 0; } count = sequence - (conn->qw.incoming_sequence + 1); if (count > 0) { droppedDatagrams += count; - Con_DPrintf("Dropped %u datagram(s)\n", count); + //Con_DPrintf("Dropped %u datagram(s)\n", count); + while (count--) + { + conn->packetlost[conn->packetlostcounter] = true; + conn->packetlostcounter = (conn->packetlostcounter + 1) % 100; + } } + conn->packetlost[conn->packetlostcounter] = false; + conn->packetlostcounter = (conn->packetlostcounter + 1) % 100; if (reliable_ack == conn->qw.reliable_sequence) { // received, now we will be able to send another reliable message @@ -845,12 +910,14 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len reliableMessagesReceived++; } conn->qw.incoming_sequence = sequence; + if (conn == cls.netcon) + cls.qw_incoming_sequence = conn->qw.incoming_sequence; conn->qw.incoming_acknowledged = sequence_ack; conn->qw.incoming_reliable_acknowledged = reliable_ack; if (reliable_message) conn->qw.incoming_reliable_sequence ^= 1; conn->lastMessageTime = realtime; - conn->timeout = realtime + net_messagetimeout.value; + conn->timeout = realtime + newtimeout; unreliableMessagesReceived++; SZ_Clear(&net_message); SZ_Write(&net_message, data, length); @@ -882,11 +949,18 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len { count = sequence - conn->nq.unreliableReceiveSequence; droppedDatagrams += count; - Con_DPrintf("Dropped %u datagram(s)\n", count); + //Con_DPrintf("Dropped %u datagram(s)\n", count); + while (count--) + { + conn->packetlost[conn->packetlostcounter] = true; + conn->packetlostcounter = (conn->packetlostcounter + 1) % 100; + } } + conn->packetlost[conn->packetlostcounter] = false; + conn->packetlostcounter = (conn->packetlostcounter + 1) % 100; conn->nq.unreliableReceiveSequence = sequence + 1; conn->lastMessageTime = realtime; - conn->timeout = realtime + net_messagetimeout.value; + conn->timeout = realtime + newtimeout; unreliableMessagesReceived++; if (length > 0) { @@ -896,8 +970,8 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len return 2; } } - else - Con_DPrint("Got a stale datagram\n"); + //else + // Con_DPrint("Got a stale datagram\n"); return 1; } else if (flags & NETFLAG_ACK) @@ -910,7 +984,7 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len if (conn->nq.ackSequence != conn->nq.sendSequence) Con_DPrint("ack sequencing error\n"); conn->lastMessageTime = realtime; - conn->timeout = realtime + net_messagetimeout.value; + conn->timeout = realtime + newtimeout; if (conn->sendMessageLength > MAX_PACKETFRAGMENT) { unsigned int packetLen; @@ -950,11 +1024,11 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len else conn->sendMessageLength = 0; } - else - Con_DPrint("Duplicate ACK received\n"); + //else + // Con_DPrint("Duplicate ACK received\n"); } - else - Con_DPrint("Stale ACK received\n"); + //else + // Con_DPrint("Stale ACK received\n"); return 1; } else if (flags & NETFLAG_DATA) @@ -966,7 +1040,7 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len if (sequence == conn->nq.receiveSequence) { conn->lastMessageTime = realtime; - conn->timeout = realtime + net_messagetimeout.value; + conn->timeout = realtime + newtimeout; conn->nq.receiveSequence++; if( conn->receiveMessageLength + length <= (int)sizeof( conn->receiveMessage ) ) { memcpy(conn->receiveMessage + conn->receiveMessageLength, data, length); @@ -1020,6 +1094,18 @@ void NetConn_ConnectionEstablished(lhnetsocket_t *mysocket, lhnetaddress_t *peer cls.protocol = initialprotocol; if (cls.protocol == PROTOCOL_QUAKEWORLD) Cmd_ForwardStringToServer("new"); + if (cls.protocol == PROTOCOL_QUAKE) + { + // write a keepalive (clc_nop) as it seems to greatly improve the + // chances of connecting to a netquake server + sizebuf_t msg; + unsigned char buf[4]; + memset(&msg, 0, sizeof(msg)); + msg.data = buf; + msg.maxsize = sizeof(buf); + MSG_WriteChar(&msg, clc_nop); + NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol); + } } int NetConn_IsLocalGame(void) @@ -1029,17 +1115,75 @@ int NetConn_IsLocalGame(void) return false; } +static int NetConn_ClientParsePacket_ServerList_ProcessReply(const char *addressstring) +{ + int n; + int pingtime; + // search the cache for this server and update it + for (n = 0;n < serverlist_cachecount;n++) + if (!strcmp(addressstring, serverlist_cache[n].info.cname)) + break; + if (n == serverlist_cachecount) + { + // LAN search doesnt require an answer from the master server so we wont + // know the ping nor will it be initialized already... + + // find a slot + if (serverlist_cachecount == SERVERLIST_TOTALSIZE) + return -1; + + memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount])); + // store the data the engine cares about (address and ping) + strlcpy(serverlist_cache[serverlist_cachecount].info.cname, addressstring, sizeof(serverlist_cache[serverlist_cachecount].info.cname)); + serverlist_cache[serverlist_cachecount].info.ping = 100000; + //serverlist_cache[serverlist_cachecount].querytime = realtime; + serverlist_cache[serverlist_cachecount].querytime = Sys_DoubleTime(); + // if not in the slist menu we should print the server to console + if (serverlist_consoleoutput) + Con_Printf("querying %s\n", addressstring); + ++serverlist_cachecount; + } + // if this is the first reply from this server, count it as having replied + if (serverlist_cache[n].info.ping == 100000) + serverreplycount++; + pingtime = (int)((Sys_DoubleTime() - serverlist_cache[n].querytime) * 1000.0 + 0.5); + pingtime = bound(0, pingtime, 9999); + // update the ping + serverlist_cache[n].info.ping = min(serverlist_cache[n].info.ping, pingtime); + // other server info is updated by the caller + return n; +} + +static void NetConn_ClientParsePacket_ServerList_UpdateCache(int n) +{ + serverlist_info_t *info = &serverlist_cache[n].info; + // update description strings for engine menu and console output + 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); + 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); + if (serverlist_cache[n].query == SQS_QUERIED) + ServerList_ViewList_Remove(&serverlist_cache[n]); + // if not in the slist menu we should print the server to console (if wanted) + else if( serverlist_consoleoutput ) + Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2); + // and finally, update the view set + ServerList_ViewList_Insert( &serverlist_cache[n] ); + serverlist_cache[n].query = SQS_QUERIED; +} + static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress) { qboolean fromserver; int ret, c, control; const char *s; - char *string, addressstring2[128], cname[128], ipstring[32]; + char *string, addressstring2[128], ipstring[32]; char stringbuf[16384]; // quakeworld ingame packet fromserver = cls.netcon && mysocket == cls.netcon->mysocket && !LHNETADDRESS_Compare(&cls.netcon->peeraddress, peeraddress); + // convert the address to a string incase we need it + LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); + if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255) { // received a command string - strip off the packaging and put it @@ -1051,9 +1195,7 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat stringbuf[length] = 0; string = stringbuf; - LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); - - if (developer.integer) + if (developer_networking.integer) { Con_Printf("NetConn_ClientParsePacket: %s sent us a command:\n", addressstring2); Com_HexDumpToConsole(data, length); @@ -1066,18 +1208,12 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat Protocol_Names(protocolnames, sizeof(protocolnames)); Con_Printf("\"%s\" received, sending connect request back to %s\n", string, addressstring2); M_Update_Return_Reason("Got challenge response"); + // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command) + InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2); + // TODO: add userinfo stuff here instead of using NQ commands? NetConn_WriteString(mysocket, va("\377\377\377\377connect\\protocol\\darkplaces 3\\protocols\\%s\\challenge\\%s", protocolnames, string + 10), peeraddress); return true; } - if (length > 1 && string[0] == 'c' && string[1] >= '0' && string[1] <= '9') - { - // quakeworld - LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); - Con_Printf("\"%s\" received, sending QuakeWorld connect request back to %s\n", string, addressstring2); - M_Update_Return_Reason("Got QuakeWorld challenge response"); - cls.qport = qport.integer; - NetConn_WriteString(mysocket, va("\377\377\377\377connect 28 %i %i \"%s\"\n", cls.qport, atoi(string + 1), cls.userinfo), peeraddress); - } if (length == 6 && !memcmp(string, "accept", 6) && cls.connect_trying) { // darkplaces or quake3 @@ -1085,13 +1221,6 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_DARKPLACES3); return true; } - if (length > 1 && string[0] == 'j' && cls.connect_trying) - { - // quakeworld - M_Update_Return_Reason("QuakeWorld Accepted"); - NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD); - return true; - } if (length > 7 && !memcmp(string, "reject ", 7) && cls.connect_trying) { char rejectreason[32]; @@ -1107,35 +1236,12 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat { serverlist_info_t *info; int n; - double pingtime; string += 13; - // serverlist only uses text addresses - LHNETADDRESS_ToString(peeraddress, cname, sizeof(cname), true); // search the cache for this server and update it - for( n = 0; n < serverlist_cachecount; n++ ) - if( !strcmp( cname, serverlist_cache[n].info.cname ) ) - break; - if( n == serverlist_cachecount ) { - // LAN search doesnt require an answer from the master server so we wont - // know the ping nor will it be initialized already... - - // find a slot - if( serverlist_cachecount == SERVERLIST_TOTALSIZE ) - return true; - - memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount])); - // store the data the engine cares about (address and ping) - strlcpy (serverlist_cache[serverlist_cachecount].info.cname, cname, sizeof (serverlist_cache[serverlist_cachecount].info.cname)); - serverlist_cache[serverlist_cachecount].info.ping = 100000; - serverlist_cache[serverlist_cachecount].querytime = realtime; - // if not in the slist menu we should print the server to console - if (serverlist_consoleoutput) { - Con_Printf("querying %s\n", ipstring); - } - - ++serverlist_cachecount; - } + n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2); + if (n < 0) + return true; info = &serverlist_cache[n].info; if ((s = SearchInfostring(string, "gamename" )) != NULL) strlcpy(info->game, s, sizeof (info->game));else info->game[0] = 0; @@ -1145,29 +1251,9 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat if ((s = SearchInfostring(string, "protocol" )) != NULL) info->protocol = atoi(s);else info->protocol = -1; if ((s = SearchInfostring(string, "clients" )) != NULL) info->numplayers = atoi(s);else info->numplayers = 0; if ((s = SearchInfostring(string, "sv_maxclients")) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0; + if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0; - if (info->ping == 100000) - serverreplycount++; - - pingtime = (int)((realtime - serverlist_cache[n].querytime) * 1000.0); - pingtime = bound(0, pingtime, 9999); - // update the ping - info->ping = pingtime; - - // legacy/old stuff move it to the menu ASAP - - // build description strings for the things users care about - dpsnprintf(serverlist_cache[n].line1, sizeof(serverlist_cache[n].line1), "%c%c%5d%c%c%c%3u/%3u %-65.65s", STRING_COLOR_TAG, pingtime >= 300 ? '1' : (pingtime >= 200 ? '3' : '7'), (int)pingtime, STRING_COLOR_TAG, STRING_COLOR_DEFAULT + '0', info->protocol != NET_PROTOCOL_VERSION ? '*' : ' ', info->numplayers, info->maxplayers, info->name); - dpsnprintf(serverlist_cache[n].line2, sizeof(serverlist_cache[n].line2), "%-21.21s %-19.19s %-17.17s %-20.20s", info->cname, info->game, info->mod, info->map); - if( serverlist_cache[n].query == SQS_QUERIED ) { - ServerList_ViewList_Remove( &serverlist_cache[n] ); - } - // if not in the slist menu we should print the server to console (if wanted) - else if( serverlist_consoleoutput ) - Con_Printf("%s\n%s\n", serverlist_cache[n].line1, serverlist_cache[n].line2); - // and finally, update the view set - ServerList_ViewList_Insert( &serverlist_cache[n] ); - serverlist_cache[n].query = SQS_QUERIED; + NetConn_ClientParsePacket_ServerList_UpdateCache(n); return true; } @@ -1178,14 +1264,14 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat length -= 18; masterreplycount++; if (serverlist_consoleoutput) - Con_Print("received server list...\n"); + Con_Print("received DarkPlaces server list...\n"); while (length >= 7 && data[0] == '\\' && (data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF || data[4] != 0xFF) && data[5] * 256 + data[6] != 0) { int n; - dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], (data[5] << 8) | data[6]); - if (developer.integer) - Con_Printf("Requesting info from server %s\n", ipstring); + dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[1], data[2], data[3], data[4], data[5] * 256 + data[6]); + if (serverlist_consoleoutput && developer_networking.integer) + Con_Printf("Requesting info from DarkPlaces server %s\n", ipstring); // ignore the rest of the message if the serverlist is full if( serverlist_cachecount == SERVERLIST_TOTALSIZE ) break; @@ -1198,6 +1284,7 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat serverquerycount++; memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount])); + serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_DARKPLACES7; // store the data the engine cares about (address and ping) strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname)); serverlist_cache[serverlist_cachecount].info.ping = 100000; @@ -1212,55 +1299,148 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat } // begin or resume serverlist queries serverlist_querysleep = false; + serverlist_querywaittime = realtime + 3; + return true; + } + if (!memcmp(string, "d\n", 2) && serverlist_cachecount < SERVERLIST_TOTALSIZE) + { + // Extract the IP addresses + data += 2; + length -= 2; + masterreplycount++; + if (serverlist_consoleoutput) + Con_Printf("received QuakeWorld server list from %s...\n", addressstring2); + while (length >= 6 && (data[0] != 0xFF || data[1] != 0xFF || data[2] != 0xFF || data[3] != 0xFF) && data[4] * 256 + data[5] != 0) + { + int n; + + dpsnprintf (ipstring, sizeof (ipstring), "%u.%u.%u.%u:%u", data[0], data[1], data[2], data[3], data[4] * 256 + data[5]); + if (serverlist_consoleoutput && developer_networking.integer) + Con_Printf("Requesting info from QuakeWorld server %s\n", ipstring); + // ignore the rest of the message if the serverlist is full + if( serverlist_cachecount == SERVERLIST_TOTALSIZE ) + break; + // also ignore it if we have already queried it (other master server response) + for( n = 0 ; n < serverlist_cachecount ; n++ ) + if( !strcmp( ipstring, serverlist_cache[ n ].info.cname ) ) + break; + if( n >= serverlist_cachecount ) + { + serverquerycount++; + + memset(&serverlist_cache[serverlist_cachecount], 0, sizeof(serverlist_cache[serverlist_cachecount])); + serverlist_cache[serverlist_cachecount].protocol = PROTOCOL_QUAKEWORLD; + // store the data the engine cares about (address and ping) + strlcpy (serverlist_cache[serverlist_cachecount].info.cname, ipstring, sizeof (serverlist_cache[serverlist_cachecount].info.cname)); + serverlist_cache[serverlist_cachecount].info.ping = 100000; + serverlist_cache[serverlist_cachecount].query = SQS_QUERYING; + + ++serverlist_cachecount; + } + + // move on to next address in packet + data += 6; + length -= 6; + } + // begin or resume serverlist queries + serverlist_querysleep = false; + serverlist_querywaittime = realtime + 3; + return true; + } + if (!strncmp(string, "extResponse ", 12)) + { + ++net_extresponse_count; + if(net_extresponse_count > NET_EXTRESPONSE_MAX) + net_extresponse_count = NET_EXTRESPONSE_MAX; + net_extresponse_last = (net_extresponse_last + 1) % NET_EXTRESPONSE_MAX; + dpsnprintf(net_extresponse[net_extresponse_last], sizeof(net_extresponse[net_extresponse_last]), "%s %s", addressstring2, string + 12); return true; } - /* if (!strncmp(string, "ping", 4)) { - if (developer.integer) - Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr)); + if (developer.integer >= 10) + Con_Printf("Received ping from %s, sending ack\n", addressstring2); NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress); return true; } if (!strncmp(string, "ack", 3)) return true; - */ // QuakeWorld compatibility + if (length > 1 && string[0] == 'c' && (string[1] == '-' || (string[1] >= '0' && string[1] <= '9')) && cls.connect_trying) + { + // challenge message + Con_Printf("challenge %s received, sending QuakeWorld connect request back to %s\n", string + 1, addressstring2); + M_Update_Return_Reason("Got QuakeWorld challenge response"); + cls.qw_qport = qport.integer; + // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command) + InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2); + NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qw_qport, atoi(string + 1), cls.userinfo), peeraddress); + return true; + } if (length >= 1 && string[0] == 'j' && cls.connect_trying) { // accept message - M_Update_Return_Reason("Accepted"); + M_Update_Return_Reason("QuakeWorld Accepted"); NetConn_ConnectionEstablished(mysocket, peeraddress, PROTOCOL_QUAKEWORLD); return true; } - if (length > 1 && string[0] == 'c' && string[1] >= '0' && string[1] <= '9' && cls.connect_trying) + if (length > 2 && !memcmp(string, "n\\", 2)) { - // challenge message - LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); - Con_Printf("challenge %s received, sending connect request back to %s\n", string + 1, addressstring2); - M_Update_Return_Reason("Got challenge response"); - cls.qport = qport.integer; - InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2); - InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "name", cl_name.string); - InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "topcolor", va("%i", (cl_color.integer >> 4) & 15)); - InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "bottomcolor", va("%i", (cl_color.integer) & 15)); - InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "rate", va("%i", cl_rate.integer)); - InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "msg", "1"); - InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ver", engineversion); - NetConn_WriteString(mysocket, va("\377\377\377\377connect %i %i %i \"%s\"\n", 28, cls.qport, atoi(string + 1), cls.userinfo), peeraddress); + serverlist_info_t *info; + int n; + + // qw server status + if (serverlist_consoleoutput && developer_networking.integer >= 2) + Con_Printf("QW server status from server at %s:\n%s\n", addressstring2, string + 1); + + string += 1; + // search the cache for this server and update it + n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2); + if (n < 0) + return true; + + info = &serverlist_cache[n].info; + strlcpy(info->game, "QuakeWorld", sizeof(info->game));; + if ((s = SearchInfostring(string, "*gamedir" )) != NULL) strlcpy(info->mod , s, sizeof (info->mod ));else info->mod[0] = 0; + if ((s = SearchInfostring(string, "map" )) != NULL) strlcpy(info->map , s, sizeof (info->map ));else info->map[0] = 0; + if ((s = SearchInfostring(string, "hostname" )) != NULL) strlcpy(info->name, s, sizeof (info->name));else info->name[0] = 0; + info->protocol = 0; + info->numplayers = 0; // updated below + if ((s = SearchInfostring(string, "maxclients" )) != NULL) info->maxplayers = atoi(s);else info->maxplayers = 0; + if ((s = SearchInfostring(string, "gameversion" )) != NULL) info->gameversion = atoi(s);else info->gameversion = 0; + + // count active players on server + // (we could gather more info, but we're just after the number) + s = strchr(string, '\n'); + if (s) + { + s++; + while (s < string + length) + { + for (;s < string + length && *s != '\n';s++) + ; + if (s >= string + length) + break; + info->numplayers++; + s++; + } + } + + NetConn_ClientParsePacket_ServerList_UpdateCache(n); + return true; } if (string[0] == 'n') { // qw print command - Con_Printf("QW print command from server at %s:\n", addressstring2, string + 1); + Con_Printf("QW print command from server at %s:\n%s\n", addressstring2, string + 1); } // we may not have liked the packet, but it was a command packet, so // we're done processing this packet now return true; } // quakeworld ingame packet - if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2) + if (fromserver && cls.protocol == PROTOCOL_QUAKEWORLD && length >= 8 && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2) { ret = 0; CL_ParseServerMessage(); @@ -1269,14 +1449,16 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat // netquake control packets, supported for compatibility only if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length) { + int n; + serverlist_info_t *info; + c = data[4]; data += 5; length -= 5; - LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); switch (c) { case CCREP_ACCEPT: - if (developer.integer) + if (developer.integer >= 10) Con_Printf("Datagram_ParseConnectionless: received CCREP_ACCEPT from %s.\n", addressstring2); if (cls.connect_trying) { @@ -1289,62 +1471,51 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat length -= 4; LHNETADDRESS_SetPort(&clientportaddress, port); } + // update the server IP in the userinfo (QW servers expect this, and it is used by the reconnect command) + InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), "*ip", addressstring2); M_Update_Return_Reason("Accepted"); NetConn_ConnectionEstablished(mysocket, &clientportaddress, PROTOCOL_QUAKE); } break; case CCREP_REJECT: - if (developer.integer) + if (developer.integer >= 10) Con_Printf("Datagram_ParseConnectionless: received CCREP_REJECT from %s.\n", addressstring2); cls.connect_trying = false; M_Update_Return_Reason((char *)data); break; -#if 0 case CCREP_SERVER_INFO: - if (developer.integer) + if (developer.integer >= 10) Con_Printf("Datagram_ParseConnectionless: received CCREP_SERVER_INFO from %s.\n", addressstring2); - if (cls.state != ca_dedicated) - { - // LordHavoc: because the UDP driver reports 0.0.0.0:26000 as the address - // string we just ignore it and keep the real address - MSG_ReadString(); - // serverlist only uses text addresses - cname = UDP_AddrToString(readaddr); - // search the cache for this server - for (n = 0; n < hostCacheCount; n++) - if (!strcmp(cname, serverlist[n].cname)) - break; - // add it - if (n == hostCacheCount && hostCacheCount < SERVERLISTSIZE) - { - hostCacheCount++; - memset(&serverlist[n], 0, sizeof(serverlist[n])); - strlcpy (serverlist[n].name, MSG_ReadString(), sizeof (serverlist[n].name)); - strlcpy (serverlist[n].map, MSG_ReadString(), sizeof (serverlist[n].map)); - serverlist[n].users = MSG_ReadByte(); - serverlist[n].maxusers = MSG_ReadByte(); - c = MSG_ReadByte(); - if (c != NET_PROTOCOL_VERSION) - { - strlcpy (serverlist[n].cname, serverlist[n].name, sizeof (serverlist[n].cname)); - strcpy(serverlist[n].name, "*"); - strlcat (serverlist[n].name, serverlist[n].cname, sizeof(serverlist[n].name)); - } - strlcpy (serverlist[n].cname, cname, sizeof (serverlist[n].cname)); - } - } + // LordHavoc: because the quake server may report weird addresses + // we just ignore it and keep the real address + MSG_ReadString(); + // search the cache for this server and update it + n = NetConn_ClientParsePacket_ServerList_ProcessReply(addressstring2); + if (n < 0) + break; + + info = &serverlist_cache[n].info; + strlcpy(info->game, "Quake", sizeof(info->game)); + strlcpy(info->mod , "", sizeof(info->mod)); // mod name is not specified + strlcpy(info->name, MSG_ReadString(), sizeof(info->name)); + strlcpy(info->map , MSG_ReadString(), sizeof(info->map)); + info->numplayers = MSG_ReadByte(); + info->maxplayers = MSG_ReadByte(); + info->protocol = MSG_ReadByte(); + + NetConn_ClientParsePacket_ServerList_UpdateCache(n); + break; case CCREP_PLAYER_INFO: // we got a CCREP_PLAYER_INFO?? - //if (developer.integer) + //if (developer.integer >= 10) Con_Printf("Datagram_ParseConnectionless: received CCREP_PLAYER_INFO from %s.\n", addressstring2); break; case CCREP_RULE_INFO: // we got a CCREP_RULE_INFO?? - //if (developer.integer) + //if (developer.integer >= 10) Con_Printf("Datagram_ParseConnectionless: received CCREP_RULE_INFO from %s.\n", addressstring2); break; -#endif default: break; } @@ -1353,7 +1524,7 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat return true; } ret = 0; - if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol)) == 2) + if (fromserver && length >= (int)NET_HEADERSIZE && (ret = NetConn_ReceivedMessage(cls.netcon, data, length, cls.protocol, net_messagetimeout.value)) == 2) CL_ParseServerMessage(); return ret; } @@ -1369,8 +1540,13 @@ void NetConn_QueryQueueFrame(void) if (serverlist_querysleep) return; + // apply a cool down time after master server replies, + // to avoid messing up the ping times on the servers + if (serverlist_querywaittime > realtime) + return; + // each time querycounter reaches 1.0 issue a query - querycounter += host_realframetime * net_slist_queriespersecond.value; + querycounter += cl.realframetime * net_slist_queriespersecond.value; maxqueries = (int)querycounter; maxqueries = bound(0, maxqueries, net_slist_queriesperframe.integer); querycounter -= maxqueries; @@ -1403,11 +1579,19 @@ void NetConn_QueryQueueFrame(void) int socket; LHNETADDRESS_FromString(&address, entry->info.cname, 0); - for (socket = 0; socket < cl_numsockets ; socket++) { - NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address); + if (entry->protocol == PROTOCOL_QUAKEWORLD) + { + for (socket = 0; socket < cl_numsockets ; socket++) + NetConn_WriteString(cl_sockets[socket], "\377\377\377\377status\n", &address); + } + else + { + for (socket = 0; socket < cl_numsockets ; socket++) + NetConn_WriteString(cl_sockets[socket], "\377\377\377\377getinfo", &address); } - entry->querytime = realtime; + //entry->querytime = realtime; + entry->querytime = Sys_DoubleTime(); entry->querycounter++; // if not in the slist menu we should print the server to console @@ -1502,12 +1686,12 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg // TODO: we should add more information for the full status string length = dpsnprintf(out_msg, out_size, "\377\377\377\377%s\x0A" - "\\gamename\\%s\\modname\\%s\\sv_maxclients\\%d" - "\\clients\\%d\\mapname\\%s\\hostname\\%s""\\protocol\\%d" + "\\gamename\\%s\\modname\\%s\\gameversion\\%d\\sv_maxclients\\%d" + "\\clients\\%d\\mapname\\%s\\hostname\\%s\\protocol\\%d" "%s%s" "%s", fullstatus ? "statusResponse" : "infoResponse", - gamename, com_modname, svs.maxclients, + gamename, com_modname, gameversion.integer, svs.maxclients, nb_clients, sv.name, hostname.string, NET_PROTOCOL_VERSION, challenge ? "\\challenge\\" : "", challenge ? challenge : "", fullstatus ? "\n" : ""); @@ -1529,7 +1713,7 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg client_t *cl = &svs.clients[i]; if (cl->active) { - int nameind, cleanind; + int nameind, cleanind, pingvalue; char curchar; char cleanname [sizeof(cl->name)]; @@ -1547,9 +1731,14 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg } } while (curchar != '\0'); + pingvalue = (int)(cl->ping * 1000.0f); + if(cl->netconnection) + pingvalue = bound(1, pingvalue, 9999); + else + pingvalue = 0; length = dpsnprintf(ptr, left, "%d %d \"%s\"\n", cl->frags, - (int)(cl->ping * 1000.0f), + pingvalue, cleanname); if(length < 0) return false; @@ -1562,15 +1751,80 @@ static qboolean NetConn_BuildStatusResponse(const char* challenge, char* out_msg return true; } +static qboolean NetConn_PreventConnectFlood(lhnetaddress_t *peeraddress) +{ + int floodslotnum, bestfloodslotnum; + double bestfloodtime; + lhnetaddress_t noportpeeraddress; + // see if this is a connect flood + noportpeeraddress = *peeraddress; + LHNETADDRESS_SetPort(&noportpeeraddress, 0); + bestfloodslotnum = 0; + bestfloodtime = sv.connectfloodaddresses[bestfloodslotnum].lasttime; + for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++) + { + if (bestfloodtime >= sv.connectfloodaddresses[floodslotnum].lasttime) + { + bestfloodtime = sv.connectfloodaddresses[floodslotnum].lasttime; + bestfloodslotnum = floodslotnum; + } + if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0) + { + // this address matches an ongoing flood address + if (realtime < sv.connectfloodaddresses[floodslotnum].lasttime + net_connectfloodblockingtimeout.value) + { + // renew the ban on this address so it does not expire + // until the flood has subsided + sv.connectfloodaddresses[floodslotnum].lasttime = realtime; + //Con_Printf("Flood detected!\n"); + return true; + } + // the flood appears to have subsided, so allow this + bestfloodslotnum = floodslotnum; // reuse the same slot + break; + } + } + // begin a new timeout on this address + sv.connectfloodaddresses[bestfloodslotnum].address = noportpeeraddress; + sv.connectfloodaddresses[bestfloodslotnum].lasttime = realtime; + //Con_Printf("Flood detection initiated!\n"); + return false; +} + +void NetConn_ClearConnectFlood(lhnetaddress_t *peeraddress) +{ + int floodslotnum; + lhnetaddress_t noportpeeraddress; + // see if this is a connect flood + noportpeeraddress = *peeraddress; + LHNETADDRESS_SetPort(&noportpeeraddress, 0); + for (floodslotnum = 0;floodslotnum < MAX_CONNECTFLOODADDRESSES;floodslotnum++) + { + if (sv.connectfloodaddresses[floodslotnum].lasttime && LHNETADDRESS_Compare(&noportpeeraddress, &sv.connectfloodaddresses[floodslotnum].address) == 0) + { + // this address matches an ongoing flood address + // remove the ban + sv.connectfloodaddresses[floodslotnum].address.addresstype = LHNETADDRESSTYPE_NONE; + sv.connectfloodaddresses[floodslotnum].lasttime = 0; + //Con_Printf("Flood cleared!\n"); + } + } +} + extern void SV_SendServerinfo (client_t *client); static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *data, int length, lhnetaddress_t *peeraddress) { int i, ret, clientnum, best; double besttime; client_t *client; - netconn_t *conn; char *s, *string, response[1400], addressstring2[128], stringbuf[16384]; + if (!sv.active) + return false; + + // convert the address to a string incase we need it + LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); + // see if we can identify the sender as a local player // (this is necessary for rcon to send a reliable reply if the client is // actually on the server, not sending remotely) @@ -1580,431 +1834,434 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat if (i == svs.maxclients) host_client = NULL; - if (sv.active) + if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255) { - if (length >= 5 && data[0] == 255 && data[1] == 255 && data[2] == 255 && data[3] == 255) + // received a command string - strip off the packaging and put it + // into our string buffer with NULL termination + data += 4; + length -= 4; + length = min(length, (int)sizeof(stringbuf) - 1); + memcpy(stringbuf, data, length); + stringbuf[length] = 0; + string = stringbuf; + + if (developer.integer >= 10) { - // received a command string - strip off the packaging and put it - // into our string buffer with NULL termination - data += 4; - length -= 4; - length = min(length, (int)sizeof(stringbuf) - 1); - memcpy(stringbuf, data, length); - stringbuf[length] = 0; - string = stringbuf; - - if (developer.integer) + Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2); + Com_HexDumpToConsole(data, length); + } + + if (length >= 12 && !memcmp(string, "getchallenge", 12) && sv_public.integer > -2) + { + for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++) + { + if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address)) + break; + if (besttime > challenge[i].time) + besttime = challenge[best = i].time; + } + // if we did not find an exact match, choose the oldest and + // update address and string + if (i == MAX_CHALLENGES) { - LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); - Con_Printf("NetConn_ServerParsePacket: %s sent us a command:\n", addressstring2); - Com_HexDumpToConsole(data, length); + i = best; + challenge[i].address = *peeraddress; + NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string)); } + challenge[i].time = realtime; + // send the challenge + NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress); + return true; + } + if (length > 8 && !memcmp(string, "connect\\", 8) && sv_public.integer > -2) + { + string += 7; + length -= 7; + + if (!(s = SearchInfostring(string, "challenge"))) + return true; + // validate the challenge + for (i = 0;i < MAX_CHALLENGES;i++) + if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s)) + break; + // if the challenge is not recognized, drop the packet + if (i == MAX_CHALLENGES) + return true; - if (length >= 12 && !memcmp(string, "getchallenge", 12)) + // check engine protocol + if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3")) { - for (i = 0, best = 0, besttime = realtime;i < MAX_CHALLENGES;i++) - { - if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address)) - break; - if (besttime > challenge[i].time) - besttime = challenge[best = i].time; - } - // if we did not find an exact match, choose the oldest and - // update address and string - if (i == MAX_CHALLENGES) - { - i = best; - challenge[i].address = *peeraddress; - NetConn_BuildChallengeString(challenge[i].string, sizeof(challenge[i].string)); - } - challenge[i].time = realtime; - // send the challenge - NetConn_WriteString(mysocket, va("\377\377\377\377challenge %s", challenge[i].string), peeraddress); + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2); + NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress); return true; } - if (length > 8 && !memcmp(string, "connect\\", 8)) + + // see if this is a duplicate connection request or a disconnected + // client who is rejoining to the same client slot + for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) { - string += 7; - length -= 7; - if ((s = SearchInfostring(string, "challenge"))) + if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0) { - // validate the challenge - for (i = 0;i < MAX_CHALLENGES;i++) - if (!LHNETADDRESS_Compare(peeraddress, &challenge[i].address) && !strcmp(challenge[i].string, s)) - break; - if (i < MAX_CHALLENGES) + // this is a known client... + if (client->spawned) { - // check engine protocol - if (strcmp(SearchInfostring(string, "protocol"), "darkplaces 3")) - { - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending \"reject Wrong game protocol.\" to %s.\n", addressstring2); - NetConn_WriteString(mysocket, "\377\377\377\377reject Wrong game protocol.", peeraddress); - } - else - { - // see if this is a duplicate connection request - for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) - if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0) - break; - if (clientnum < svs.maxclients && realtime - client->connecttime < net_messagerejointimeout.value) - { - // client is still trying to connect, - // so we send a duplicate reply - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2); - NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress); - } -#if 0 - else if (clientnum < svs.maxclients) - { - if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value) - { - // client crashed and is coming back, keep their stuff intact - SV_SendServerinfo(client); - //host_client = client; - //SV_DropClient (true); - } - // else ignore them - } -#endif - else - { - // this is a new client, find a slot - for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) - if (!client->active) - break; - if (clientnum < svs.maxclients) - { - // prepare the client struct - if ((conn = NetConn_Open(mysocket, peeraddress))) - { - // allocated connection - LHNETADDRESS_ToString(peeraddress, conn->address, sizeof(conn->address), true); - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address); - NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress); - // now set up the client - SV_VM_Begin(); - SV_ConnectClient(clientnum, conn); - SV_VM_End(); - NetConn_Heartbeat(1); - } - } - else - { - // server is full - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2); - NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress); - } - } - } + // client crashed and is coming back, + // keep their stuff intact + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", addressstring2); + NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress); + SV_VM_Begin(); + SV_SendServerinfo(client); + SV_VM_End(); + } + else + { + // client is still trying to connect, + // so we send a duplicate reply + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending duplicate accept to %s.\n", addressstring2); + NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress); } + return true; } - return true; } - if (length >= 7 && !memcmp(string, "getinfo", 7)) - { - const char *challenge = NULL; - // If there was a challenge in the getinfo message - if (length > 8 && string[7] == ' ') - challenge = string + 8; + if (NetConn_PreventConnectFlood(peeraddress)) + return true; - if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false)) + // find an empty client slot for this new client + for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) + { + netconn_t *conn; + if (!client->active && (conn = NetConn_Open(mysocket, peeraddress))) { - if (developer.integer) - Con_Printf("Sending reply to master %s - %s\n", addressstring2, response); - NetConn_WriteString(mysocket, response, peeraddress); + // allocated connection + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending \"accept\" to %s.\n", conn->address); + NetConn_WriteString(mysocket, "\377\377\377\377accept", peeraddress); + // now set up the client + SV_VM_Begin(); + SV_ConnectClient(clientnum, conn); + SV_VM_End(); + NetConn_Heartbeat(1); + return true; } - return true; } - if (length >= 9 && !memcmp(string, "getstatus", 9)) + + // no empty slots found - server is full + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending \"reject Server is full.\" to %s.\n", addressstring2); + NetConn_WriteString(mysocket, "\377\377\377\377reject Server is full.", peeraddress); + + return true; + } + if (length >= 7 && !memcmp(string, "getinfo", 7) && sv_public.integer > -1) + { + const char *challenge = NULL; + + // If there was a challenge in the getinfo message + if (length > 8 && string[7] == ' ') + challenge = string + 8; + + if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), false)) { - const char *challenge = NULL; + if (developer.integer >= 10) + Con_Printf("Sending reply to master %s - %s\n", addressstring2, response); + NetConn_WriteString(mysocket, response, peeraddress); + } + return true; + } + if (length >= 9 && !memcmp(string, "getstatus", 9) && sv_public.integer > -1) + { + const char *challenge = NULL; - // If there was a challenge in the getinfo message - if (length > 10 && string[9] == ' ') - challenge = string + 10; + // If there was a challenge in the getinfo message + if (length > 10 && string[9] == ' ') + challenge = string + 10; - if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true)) - { - if (developer.integer) - Con_Printf("Sending reply to client %s - %s\n", addressstring2, response); - NetConn_WriteString(mysocket, response, peeraddress); - } - return true; + if (NetConn_BuildStatusResponse(challenge, response, sizeof(response), true)) + { + if (developer.integer >= 10) + Con_Printf("Sending reply to client %s - %s\n", addressstring2, response); + NetConn_WriteString(mysocket, response, peeraddress); } - if (length >= 5 && !memcmp(string, "rcon ", 5)) + return true; + } + if (length >= 5 && !memcmp(string, "rcon ", 5)) + { + int i; + char *s = string + 5; + char password[64]; + for (i = 0;*s > ' ';s++) + if (i < (int)sizeof(password) - 1) + password[i++] = *s; + password[i] = 0; + if (password[0] > ' ' && !strcmp(rcon_password.string, password)) { - int i; - char *s = string + 5; - char password[64]; - for (i = 0;*s > ' ';s++) - if (i < (int)sizeof(password) - 1) - password[i++] = *s; - password[i] = 0; - if (password[0] > ' ' && !strcmp(rcon_password.string, password)) + // looks like a legitimate rcon command with the correct password + Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s); + rcon_redirect = true; + rcon_redirect_bufferpos = 0; + Cmd_ExecuteString(s, src_command); + rcon_redirect_buffer[rcon_redirect_bufferpos] = 0; + rcon_redirect = false; + // print resulting text to client + // if client is playing, send a reliable reply instead of + // a command packet + if (host_client) { - // looks like a legitimate rcon command with the correct password - Con_Printf("server received rcon command from %s:\n%s\n", host_client ? host_client->name : addressstring2, s); - rcon_redirect = true; - rcon_redirect_bufferpos = 0; - Cmd_ExecuteString(s, src_command); - rcon_redirect_buffer[rcon_redirect_bufferpos] = 0; - rcon_redirect = false; - // print resulting text to client - // if client is playing, send a reliable reply instead of - // a command packet - if (host_client) - { - // if the netconnection is loop, then this is the - // local player on a listen mode server, and it would - // result in duplicate printing to the console - // (not that the local player should be using rcon - // when they have the console) - if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP) - SV_ClientPrintf("%s", rcon_redirect_buffer); - } - else - { - // qw print command - dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer); - NetConn_WriteString(mysocket, response, peeraddress); - } + // if the netconnection is loop, then this is the + // local player on a listen mode server, and it would + // result in duplicate printing to the console + // (not that the local player should be using rcon + // when they have the console) + if (host_client->netconnection && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP) + SV_ClientPrintf("%s", rcon_redirect_buffer); + } + else + { + // qw print command + dpsnprintf(response, sizeof(response), "\377\377\377\377n%s", rcon_redirect_buffer); + NetConn_WriteString(mysocket, response, peeraddress); } - return true; - } - /* - if (!strncmp(string, "ping", 4)) - { - if (developer.integer) - Con_Printf("Received ping from %s, sending ack\n", UDP_AddrToString(readaddr)); - NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress); - return true; } - if (!strncmp(string, "ack", 3)) - return true; - */ - // we may not have liked the packet, but it was a command packet, so - // we're done processing this packet now return true; } - // LordHavoc: disabled netquake control packet support in server -#if 0 + if (!strncmp(string, "ping", 4)) + { + if (developer.integer >= 10) + Con_Printf("Received ping from %s, sending ack\n", addressstring2); + NetConn_WriteString(mysocket, "\377\377\377\377ack", peeraddress); + return true; + } + if (!strncmp(string, "ack", 3)) + return true; + // we may not have liked the packet, but it was a command packet, so + // we're done processing this packet now + return true; + } + // netquake control packets, supported for compatibility only, and only + // when running game protocols that are normally served via this connection + // protocol + // (this protects more modern protocols against being used for + // Quake packet flood Denial Of Service attacks) + 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)) + { + int c = data[4]; + data += 5; + length -= 5; + switch (c) { - int c, control; - // netquake control packets, supported for compatibility only - if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length) + case CCREQ_CONNECT: + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2); + if (length < (int)strlen("QUAKE") + 1 + 1) + break; + if(sv_public.integer <= -2) + break; + + if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION) + { + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2); + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_REJECT); + MSG_WriteString(&net_message, "Incompatible version.\n"); + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); + SZ_Clear(&net_message); + break; + } + + // see if this connect request comes from a known client + for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) { - c = data[4]; - data += 5; - length -= 5; - LHNETADDRESS_ToString(peeraddress, addressstring2, sizeof(addressstring2), true); - switch (c) + if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0) { - case CCREQ_CONNECT: - //if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: received CCREQ_CONNECT from %s.\n", addressstring2); - if (length >= (int)strlen("QUAKE") + 1 + 1) + // this is either a duplicate connection request + // or coming back from a timeout + // (if so, keep their stuff intact) + + // send a reply + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2); + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_ACCEPT); + MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket))); + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); + SZ_Clear(&net_message); + + // if client is already spawned, re-send the + // serverinfo message as they'll need it to play + if (client->spawned) { - if (memcmp(data, "QUAKE", strlen("QUAKE") + 1) != 0 || (int)data[strlen("QUAKE") + 1] != NET_PROTOCOL_VERSION) - { - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Incompatible version.\" to %s.\n", addressstring2); - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_REJECT); - MSG_WriteString(&net_message, "Incompatible version.\n"); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); - SZ_Clear(&net_message); - } - else - { - // see if this is a duplicate connection request - for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) - if (client->netconnection && LHNETADDRESS_Compare(peeraddress, &client->netconnection->peeraddress) == 0) - break; - if (clientnum < svs.maxclients) - { - // duplicate connection request - if (realtime - client->connecttime < 2.0) - { - // client is still trying to connect, - // so we send a duplicate reply - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending duplicate CCREP_ACCEPT to %s.\n", addressstring2); - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_ACCEPT); - MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket))); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); - SZ_Clear(&net_message); - } -#if 0 - else if (realtime - client->netconnection->lastMessageTime >= net_messagerejointimeout.value) - { - SV_SendServerinfo(client); - // the old client hasn't sent us anything - // in quite a while, so kick off and let - // the retry take care of it... - //host_client = client; - //SV_DropClient (true); - } -#endif - } - else - { - // this is a new client, find a slot - for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) - if (!client->active) - break; - if (clientnum < svs.maxclients && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL) - { - // connect to the client - // everything is allocated, just fill in the details - strlcpy (conn->address, addressstring2, sizeof (conn->address)); - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2); - // send back the info about the server connection - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_ACCEPT); - MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket))); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); - SZ_Clear(&net_message); - // now set up the client struct - SV_VM_Begin(); - SV_ConnectClient(clientnum, conn); - SV_VM_End(); - NetConn_Heartbeat(1); - } - else - { - //if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2); - // no room; try to let player know - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_REJECT); - MSG_WriteString(&net_message, "Server is full.\n"); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); - SZ_Clear(&net_message); - } - } - } - } - break; -#if 0 - case CCREQ_SERVER_INFO: - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2); - if (sv.active && !strcmp(MSG_ReadString(), "QUAKE")) - { - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2); - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_SERVER_INFO); - UDP_GetSocketAddr(UDP_acceptSock, &newaddr); - MSG_WriteString(&net_message, UDP_AddrToString(&newaddr)); - MSG_WriteString(&net_message, hostname.string); - MSG_WriteString(&net_message, sv.name); - MSG_WriteByte(&net_message, net_activeconnections); - MSG_WriteByte(&net_message, svs.maxclients); - MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); - SZ_Clear(&net_message); - } - break; - case CCREQ_PLAYER_INFO: - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2); - if (sv.active) - { - int playerNumber, activeNumber, clientNumber; - client_t *client; - - playerNumber = MSG_ReadByte(); - activeNumber = -1; - for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++) - if (client->active && ++activeNumber == playerNumber) - break; - if (clientNumber != svs.maxclients) - { - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_PLAYER_INFO); - MSG_WriteByte(&net_message, playerNumber); - MSG_WriteString(&net_message, client->name); - MSG_WriteLong(&net_message, client->colors); - MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags); - MSG_WriteLong(&net_message, (int)(realtime - client->connecttime)); - MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient"); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); - SZ_Clear(&net_message); - } + SV_VM_Begin(); + SV_SendServerinfo(client); + SV_VM_End(); } - break; - case CCREQ_RULE_INFO: - if (developer.integer) - Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2); - if (sv.active) - { - char *prevCvarName; - cvar_t *var; + return true; + } + } - // find the search start location - prevCvarName = MSG_ReadString(); - var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY); + // this is a new client, check for connection flood + if (NetConn_PreventConnectFlood(peeraddress)) + break; - // send the response - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREP_RULE_INFO); - if (var) - { - MSG_WriteString(&net_message, var->name); - MSG_WriteString(&net_message, var->string); - } - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); - SZ_Clear(&net_message); - } - break; -#endif - default: - break; + // find a slot for the new client + for (clientnum = 0, client = svs.clients;clientnum < svs.maxclients;clientnum++, client++) + { + netconn_t *conn; + if (!client->active && (client->netconnection = conn = NetConn_Open(mysocket, peeraddress)) != NULL) + { + // connect to the client + // everything is allocated, just fill in the details + strlcpy (conn->address, addressstring2, sizeof (conn->address)); + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending CCREP_ACCEPT to %s.\n", addressstring2); + // send back the info about the server connection + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_ACCEPT); + MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket))); + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); + SZ_Clear(&net_message); + // now set up the client struct + SV_VM_Begin(); + SV_ConnectClient(clientnum, conn); + SV_VM_End(); + NetConn_Heartbeat(1); + return true; } - // we may not have liked the packet, but it was a valid control - // packet, so we're done processing this packet now - return true; } - } -#endif - if (host_client) - { - if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol)) == 2) + + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending CCREP_REJECT \"Server is full.\" to %s.\n", addressstring2); + // no room; try to let player know + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_REJECT); + MSG_WriteString(&net_message, "Server is full.\n"); + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); + SZ_Clear(&net_message); + break; + case CCREQ_SERVER_INFO: + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: received CCREQ_SERVER_INFO from %s.\n", addressstring2); + if(sv_public.integer <= -1) + break; + if (sv.active && !strcmp(MSG_ReadString(), "QUAKE")) { - SV_VM_Begin(); - SV_ReadClientMessage(); - SV_VM_End(); - return ret; + int numclients; + char myaddressstring[128]; + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: sending CCREP_SERVER_INFO to %s.\n", addressstring2); + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_SERVER_INFO); + LHNETADDRESS_ToString(LHNET_AddressFromSocket(mysocket), myaddressstring, sizeof(myaddressstring), true); + MSG_WriteString(&net_message, myaddressstring); + MSG_WriteString(&net_message, hostname.string); + MSG_WriteString(&net_message, sv.name); + // How many clients are there? + for (i = 0, numclients = 0;i < svs.maxclients;i++) + if (svs.clients[i].active) + numclients++; + MSG_WriteByte(&net_message, numclients); + MSG_WriteByte(&net_message, svs.maxclients); + MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); + SZ_Clear(&net_message); } + break; + case CCREQ_PLAYER_INFO: + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: received CCREQ_PLAYER_INFO from %s.\n", addressstring2); + if(sv_public.integer <= -1) + break; + if (sv.active) + { + int playerNumber, activeNumber, clientNumber; + client_t *client; + + playerNumber = MSG_ReadByte(); + activeNumber = -1; + for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++) + if (client->active && ++activeNumber == playerNumber) + break; + if (clientNumber != svs.maxclients) + { + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_PLAYER_INFO); + MSG_WriteByte(&net_message, playerNumber); + MSG_WriteString(&net_message, client->name); + MSG_WriteLong(&net_message, client->colors); + MSG_WriteLong(&net_message, (int)client->edict->fields.server->frags); + MSG_WriteLong(&net_message, (int)(realtime - client->connecttime)); + MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient"); + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); + SZ_Clear(&net_message); + } + } + break; + case CCREQ_RULE_INFO: + if (developer.integer >= 10) + Con_Printf("Datagram_ParseConnectionless: received CCREQ_RULE_INFO from %s.\n", addressstring2); + if(sv_public.integer <= -1) + break; + if (sv.active) + { + char *prevCvarName; + cvar_t *var; + + // find the search start location + prevCvarName = MSG_ReadString(); + var = Cvar_FindVarAfter(prevCvarName, CVAR_NOTIFY); + + // send the response + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREP_RULE_INFO); + if (var) + { + MSG_WriteString(&net_message, var->name); + MSG_WriteString(&net_message, var->string); + } + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress); + SZ_Clear(&net_message); + } + break; + default: + break; + } + // we may not have liked the packet, but it was a valid control + // packet, so we're done processing this packet now + return true; + } + if (host_client) + { + if ((ret = NetConn_ReceivedMessage(host_client->netconnection, data, length, sv.protocol, host_client->spawned ? net_messagetimeout.value : net_connecttimeout.value)) == 2) + { + SV_VM_Begin(); + SV_ReadClientMessage(); + SV_VM_End(); + return ret; } } return 0; @@ -2014,7 +2271,6 @@ void NetConn_ServerFrame(void) { int i, length; lhnetaddress_t peeraddress; - NetConn_UpdateSockets(); for (i = 0;i < sv_numsockets;i++) while (sv_sockets[i] && (length = NetConn_Read(sv_sockets[i], readbuffer, sizeof(readbuffer), &peeraddress)) > 0) NetConn_ServerParsePacket(sv_sockets[i], readbuffer, length, &peeraddress); @@ -2024,12 +2280,14 @@ void NetConn_ServerFrame(void) if (host_client->netconnection && realtime > host_client->netconnection->timeout && LHNETADDRESS_GetAddressType(&host_client->netconnection->peeraddress) != LHNETADDRESSTYPE_LOOP) { Con_Printf("Client \"%s\" connection timed out\n", host_client->name); + SV_VM_Begin(); SV_DropClient(false); + SV_VM_End(); } } } -void NetConn_QueryMasters(void) +void NetConn_QueryMasters(qboolean querydp, qboolean queryqw) { int i; int masternum; @@ -2045,34 +2303,70 @@ void NetConn_QueryMasters(void) // note this is IPv4-only, I doubt there are IPv6-only LANs out there LHNETADDRESS_FromString(&broadcastaddress, "255.255.255.255", 26000); - for (i = 0;i < cl_numsockets;i++) + if (querydp) { - if (cl_sockets[i]) + for (i = 0;i < cl_numsockets;i++) { - // search LAN for Quake servers - SZ_Clear(&net_message); - // save space for the header, filled in later - MSG_WriteLong(&net_message, 0); - MSG_WriteByte(&net_message, CCREQ_SERVER_INFO); - MSG_WriteString(&net_message, "QUAKE"); - MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); - *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); - NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress); - SZ_Clear(&net_message); + if (cl_sockets[i]) + { + // search LAN for Quake servers + SZ_Clear(&net_message); + // save space for the header, filled in later + MSG_WriteLong(&net_message, 0); + MSG_WriteByte(&net_message, CCREQ_SERVER_INFO); + MSG_WriteString(&net_message, "QUAKE"); + MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); + *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); + NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress); + SZ_Clear(&net_message); + + // search LAN for DarkPlaces servers + NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress); + + // build the getservers message to send to the dpmaster master servers + dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION); + + // search internet + for (masternum = 0;sv_masters[masternum].name;masternum++) + { + 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]))) + { + masterquerycount++; + NetConn_WriteString(cl_sockets[i], request, &masteraddress); + } + } + } + } + } - // search LAN for DarkPlaces servers - NetConn_WriteString(cl_sockets[i], "\377\377\377\377getinfo", &broadcastaddress); + // only query QuakeWorld servers when the user wants to + if (queryqw) + { + for (i = 0;i < cl_numsockets;i++) + { + if (cl_sockets[i]) + { + // search LAN for QuakeWorld servers + NetConn_WriteString(cl_sockets[i], "\377\377\377\377status\n", &broadcastaddress); - // build the getservers message to send to the master servers - dpsnprintf(request, sizeof(request), "\377\377\377\377getservers %s %u empty full\x0A", gamename, NET_PROTOCOL_VERSION); + // build the getservers message to send to the qwmaster master servers + // note this has no -1 prefix, and the trailing nul byte is sent + dpsnprintf(request, sizeof(request), "c\n"); - // search internet - for (masternum = 0;sv_masters[masternum].name;masternum++) - { - if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]))) + // search internet + for (masternum = 0;sv_qwmasters[masternum].name;masternum++) { - masterquerycount++; - NetConn_WriteString(cl_sockets[i], request, &masteraddress); + if (sv_qwmasters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_qwmasters[masternum].string, QWMASTER_PORT) && LHNETADDRESS_GetAddressType(&masteraddress) == LHNETADDRESS_GetAddressType(LHNET_AddressFromSocket(cl_sockets[i]))) + { + if (m_state != m_slist) + { + char lookupstring[128]; + LHNETADDRESS_ToString(&masteraddress, lookupstring, sizeof(lookupstring), true); + Con_Printf("Querying master %s (resolved from %s)\n", lookupstring, sv_qwmasters[masternum].string); + } + masterquerycount++; + NetConn_Write(cl_sockets[i], request, (int)strlen(request) + 1, &masteraddress); + } } } } @@ -2106,11 +2400,11 @@ void NetConn_Heartbeat(int priority) // make advertising optional and don't advertise singleplayer games, and // only send a heartbeat as often as the admin wants - if (sv.active && sv_public.integer && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime)) + if (sv.active && sv_public.integer > 0 && svs.maxclients >= 2 && (priority > 1 || realtime > nextheartbeattime)) { nextheartbeattime = realtime + sv_heartbeatperiod.value; for (masternum = 0;sv_masters[masternum].name;masternum++) - if (sv_masters[masternum].string && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, MASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress))) + if (sv_masters[masternum].string && sv_masters[masternum].string[0] && LHNETADDRESS_FromString(&masteraddress, sv_masters[masternum].string, DPMASTER_PORT) && (mysocket = NetConn_ChooseServerSocketForAddress(&masteraddress))) NetConn_WriteString(mysocket, "\377\377\377\377heartbeat DarkPlaces\x0A", &masteraddress); } } @@ -2155,11 +2449,25 @@ void Net_Slist_f(void) serverlist_sortdescending = false; if (m_state != m_slist) { Con_Print("Sending requests to master servers\n"); - ServerList_QueryList(); + ServerList_QueryList(true, false); + serverlist_consoleoutput = true; + Con_Print("Listening for replies...\n"); + } else + ServerList_QueryList(true, false); +} + +void Net_SlistQW_f(void) +{ + ServerList_ResetMasks(); + serverlist_sortbyfield = SLIF_PING; + serverlist_sortdescending = false; + if (m_state != m_slist) { + Con_Print("Sending requests to master servers\n"); + ServerList_QueryList(false, true); serverlist_consoleoutput = true; Con_Print("Listening for replies...\n"); } else - ServerList_QueryList(); + ServerList_QueryList(false, true); } void NetConn_Init(void) @@ -2168,15 +2476,16 @@ void NetConn_Init(void) lhnetaddress_t tempaddress; netconn_mempool = Mem_AllocPool("network connections", 0, NULL); Cmd_AddCommand("net_stats", Net_Stats_f, "print network statistics"); - Cmd_AddCommand("net_slist", Net_Slist_f, "query master series and print all server information"); + Cmd_AddCommand("net_slist", Net_Slist_f, "query dp master servers and print all server information"); + Cmd_AddCommand("net_slistqw", Net_SlistQW_f, "query qw master servers and print all server information"); Cmd_AddCommand("heartbeat", Net_Heartbeat_f, "send a heartbeat to the master server (updates your server information)"); Cvar_RegisterVariable(&net_slist_queriespersecond); Cvar_RegisterVariable(&net_slist_queriesperframe); Cvar_RegisterVariable(&net_slist_timeout); Cvar_RegisterVariable(&net_slist_maxtries); Cvar_RegisterVariable(&net_messagetimeout); - Cvar_RegisterVariable(&net_messagerejointimeout); Cvar_RegisterVariable(&net_connecttimeout); + Cvar_RegisterVariable(&net_connectfloodblockingtimeout); Cvar_RegisterVariable(&cl_netlocalping); Cvar_RegisterVariable(&cl_netpacketloss); Cvar_RegisterVariable(&hostname); @@ -2189,6 +2498,7 @@ void NetConn_Init(void) Cvar_RegisterVariable(&sv_heartbeatperiod); for (i = 0;sv_masters[i].name;i++) Cvar_RegisterVariable(&sv_masters[i]); + Cvar_RegisterVariable(&gameversion); // COMMANDLINEOPTION: Server: -ip 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. if ((i = COM_CheckParm("-ip")) && i + 1 < com_argc) {