Ejemplo n.º 1
0
        public override bool Receive(out NetworkChunk packet)
        {
            while (true)
            {
                if (ChunkReceiver.FetchChunk(out packet))
                {
                    return(true);
                }

                if (UdpClient.Available <= 0)
                {
                    return(false);
                }

                var    remote = (IPEndPoint)null;
                byte[] data;

                try
                {
                    data = UdpClient.Receive(ref remote);
                }
                catch
                {
                    continue;
                }

                if (data.Length <= 0)
                {
                    continue;
                }

                if (!NetworkCore.UnpackPacket(data, data.Length, ChunkReceiver.ChunkConstruct))
                {
                    continue;
                }

                var useToken = false;
                var token    = (uint)0;

                if (ChunkReceiver.ChunkConstruct.Flags.HasFlag(PacketFlags.TOKEN))
                {
                    useToken = true;
                    token    = ChunkReceiver.ChunkConstruct.Token;
                }
                else if (ChunkReceiver.ChunkConstruct.Flags.HasFlag(PacketFlags.CONTROL) &&
                         ChunkReceiver.ChunkConstruct.Data[0] == (int)ConnectionMessages.CONNECT &&
                         ChunkReceiver.ChunkConstruct.DataSize >= 1 + 512)
                {
                    useToken = true;
                    token    = ChunkReceiver.ChunkConstruct.Data.ToUInt32(5);
                }

                if (NetworkBan.IsBanned(remote, out var reason))
                {
                    NetworkCore.SendControlMsg(UdpClient, remote, 0, useToken, token,
                                               ConnectionMessages.CLOSE, reason);
                    continue;
                }

                if (ChunkReceiver.ChunkConstruct.Flags.HasFlag(PacketFlags.CONNLESS))
                {
                    packet = new NetworkChunk
                    {
                        ClientId = -1,
                        Flags    = SendFlags.CONNLESS,
                        EndPoint = remote,
                        DataSize = ChunkReceiver.ChunkConstruct.DataSize,
                        Data     = ChunkReceiver.ChunkConstruct.Data
                    };

                    return(true);
                }

                var clientId = FindSlot(remote, true);

                if (ChunkReceiver.ChunkConstruct.Flags.HasFlag(PacketFlags.CONTROL) &&
                    ChunkReceiver.ChunkConstruct.Data[0] == (int)ConnectionMessages.CONNECT)
                {
                    if (clientId != -1)
                    {
                        continue;
                    }

                    if (ChunkReceiver.ChunkConstruct.DataSize >= 1 + 512)
                    {
                        var connectAccept = new byte[4];
                        GetToken(remote).ToByteArray(connectAccept, 0);
                        NetworkCore.SendControlMsg(UdpClient, remote, 0, true, token,
                                                   ConnectionMessages.CONNECTACCEPT, connectAccept);
                        Debug.Log("netserver", "got connect, sending connect+accept challenge");
                    }
                    else if (Config["SvAllowOldClients"].AsBoolean() && string.IsNullOrWhiteSpace(Config["Password"].AsString()))
                    {
                        if (LegacyRateLimit())
                        {
                            Debug.Log("netserver", "dropping legacy connect due to ratelimit");
                            continue;
                        }

                        var packets = new NetworkChunkConstruct[]
                        {
                            new NetworkChunkConstruct(),
                            new NetworkChunkConstruct(),
                        };
                        var legacyToken = GetLegacyToken(remote);

                        ConstructLegacyHandshake(packets[0], packets[1], legacyToken);
                        for (var i = 0; i < 2; i++)
                        {
                            NetworkCore.SendPacket(UdpClient, remote, packets[i]);
                        }
                        Debug.Log("netserver", "got legacy connect, sending legacy challenge");
                    }
                    else
                    {
                        Debug.Log("netserver", $"dropping short connect packet, size={ChunkReceiver.ChunkConstruct.DataSize}");
                    }
                }
                else
                {
                    if (clientId == -1)
                    {
                        if (!useToken || !IsCorrectToken(remote, token))
                        {
                            if (!useToken && Config["SvAllowOldClients"].AsBoolean())
                            {
                                ChunkReceiver.Start(remote, null, -1);
                                var chunk   = new NetworkChunk();
                                var correct = false;

                                while (ChunkReceiver.FetchChunk(out chunk))
                                {
                                    if (DecodeLegacyHandShake(chunk.Data, chunk.DataSize, out var legacyToken))
                                    {
                                        if (IsCorrectLegacyToken(remote, legacyToken))
                                        {
                                            correct = true;
                                            break;
                                        }
                                    }
                                }

                                ChunkReceiver.Clear();

                                if (!correct)
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                Debug.Log("netserver",
                                          !useToken
                                        ? "dropping packet with missing token"
                                        : $"dropping packet with invalid token, token={token}");
                                continue;
                            }
                        }

                        var sameIps = 0;

                        for (var i = 0; i < Connections.Length; i++)
                        {
                            if (Connections[i].State == ConnectionState.OFFLINE)
                            {
                                if (clientId < 0)
                                {
                                    clientId = i;
                                }
                                continue;
                            }

                            if (!NetworkCore.CompareEndPoints(Connections[i].EndPoint, remote, false))
                            {
                                continue;
                            }

                            sameIps++;
                            if (sameIps >= ServerConfig.MaxClientsPerIp)
                            {
                                NetworkCore.SendControlMsg(UdpClient, remote, 0, useToken, token, ConnectionMessages.CLOSE,
                                                           $"Only {ServerConfig.MaxClientsPerIp} players with the same IP are allowed");
                                return(false);
                            }
                        }

                        if (clientId < 0)
                        {
                            for (var i = 0; i < Connections.Length; i++)
                            {
                                if (Connections[i].State == ConnectionState.OFFLINE)
                                {
                                    clientId = i;
                                    break;
                                }
                            }
                        }

                        if (clientId < 0)
                        {
                            NetworkCore.SendControlMsg(UdpClient, remote, 0, useToken, token,
                                                       ConnectionMessages.CLOSE, "This server is full");
                            return(false);
                        }

                        if (useToken)
                        {
                            Connections[clientId].Accept(remote, token);
                        }
                        else
                        {
                            Connections[clientId].AcceptLegacy(remote);
                        }

                        NewClientCallback?.Invoke(clientId, !useToken);
                        if (!useToken)
                        {
                            continue;
                        }

                        Connections[clientId].Feed(ChunkReceiver.ChunkConstruct, remote);
                    }

                    if (Connections[clientId].Feed(ChunkReceiver.ChunkConstruct, remote))
                    {
                        if (ChunkReceiver.ChunkConstruct.DataSize != 0)
                        {
                            ChunkReceiver.Start(remote, Connections[clientId], clientId);
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public override bool Receive(ref Chunk packet, ref uint responseToken)
        {
            // TODO make multithreaded
            // https://docs.microsoft.com/ru-ru/dotnet/standard/io/how-to-use-named-pipes-for-network-interprocess-communication
            // https://blogs.msdn.microsoft.com/dotnet/2018/07/09/system-io-pipelines-high-performance-io-in-net/

            while (true)
            {
                if (ChunkReceiver.FetchChunk(ref packet))
                {
                    return(true);
                }

                if (UdpClient.Available <= 0)
                {
                    return(false);
                }

                var    endPoint = default(IPEndPoint);
                byte[] data;

                try
                {
                    data = UdpClient.Receive(ref endPoint);
                }
                catch
                {
                    continue;
                }

                if (data.Length == 0)
                {
                    continue;
                }

                if (!NetworkHelper.UnpackPacket(data, data.Length, ChunkReceiver.ChunkConstruct))
                {
                    continue;
                }

                if (NetworkBan.IsBanned(endPoint, out var banReason))
                {
                    NetworkHelper.SendConnectionMsg(UdpClient, endPoint,
                                                    ChunkReceiver.ChunkConstruct.ResponseToken, 0, ConnectionMessages.Close, banReason);
                    continue;
                }

                var freeSlot  = -1;
                var foundSlot = -1;
                var sameIps   = 0;

                for (var i = 0; i < Connections.Count; i++)
                {
                    if (Connections[i].State == ConnectionState.Offline && freeSlot < 0)
                    {
                        freeSlot = i;
                    }

                    if (Connections[i].State != ConnectionState.Offline &&
                        Connections[i].EndPoint.Compare(endPoint, comparePorts: false))
                    {
                        sameIps++;

                        if (Connections[i].EndPoint.Port != endPoint.Port)
                        {
                            continue;
                        }

                        if (Connections[i].Feed(ChunkReceiver.ChunkConstruct, endPoint))
                        {
                            if (ChunkReceiver.ChunkConstruct.DataSize > 0)
                            {
                                if (ChunkReceiver.ChunkConstruct.Flags.HasFlag(PacketFlags.Connless))
                                {
                                    packet = new Chunk()
                                    {
                                        Flags    = SendFlags.Connless,
                                        EndPoint = endPoint,
                                        ClientId = i,
                                        DataSize = ChunkReceiver.ChunkConstruct.DataSize,
                                        Data     = ChunkReceiver.ChunkConstruct.Data
                                    };

                                    responseToken = TokenHelper.TokenNone;
                                    return(true);
                                }

                                ChunkReceiver.Start(endPoint, Connections[i], i);
                            }
                        }

                        foundSlot = i;
                        break;
                    }
                }

                if (foundSlot >= 0)
                {
                    continue;
                }

                var accept = TokenManager.ProcessMessage(endPoint, ChunkReceiver.ChunkConstruct);
                if (accept <= 0)
                {
                    continue;
                }

                if (ChunkReceiver.ChunkConstruct.Flags.HasFlag(PacketFlags.Control))
                {
                    if (ChunkReceiver.ChunkConstruct.Data[0] == (int)ConnectionMessages.Connect)
                    {
                        if (sameIps >= Config.MaxClientsPerIp)
                        {
                            NetworkHelper.SendConnectionMsg(UdpClient, endPoint,
                                                            ChunkReceiver.ChunkConstruct.ResponseToken, 0,
                                                            ConnectionMessages.Close, $"Only {Config.MaxClientsPerIp} players with the same IP are allowed");
                            return(false);
                        }

                        if (freeSlot >= 0)
                        {
                            Connections[freeSlot].SetToken(ChunkReceiver.ChunkConstruct.Token);
                            Connections[freeSlot].Feed(ChunkReceiver.ChunkConstruct, endPoint);
                            OnClientConnected(freeSlot);
                            continue;
                        }

                        NetworkHelper.SendConnectionMsg(UdpClient, endPoint,
                                                        ChunkReceiver.ChunkConstruct.ResponseToken, 0,
                                                        ConnectionMessages.Close, "This server is full");
                        return(false);
                    }

                    if (ChunkReceiver.ChunkConstruct.Data[0] == (int)ConnectionMessages.Token)
                    {
                        TokenCache.AddToken(endPoint, ChunkReceiver.ChunkConstruct.ResponseToken,
                                            TokenFlags.ResponseOnly);
                    }
                }
                else if (ChunkReceiver.ChunkConstruct.Flags.HasFlag(PacketFlags.Connless))
                {
                    packet = new Chunk()
                    {
                        Flags    = SendFlags.Connless,
                        ClientId = -1,
                        EndPoint = endPoint,
                        DataSize = ChunkReceiver.ChunkConstruct.DataSize,
                        Data     = ChunkReceiver.ChunkConstruct.Data,
                    };

                    responseToken = ChunkReceiver.ChunkConstruct.ResponseToken;
                    return(true);
                }
            }
        }