public void SendPackage(Package package)
        {
            MiNetServer.TraceSend(package);

            if (package == null)
            {
                return;
            }

            if (State == ConnectionState.Unconnected)
            {
                package.PutPool();
                return;
            }

            bool isBatch = package is McpeBatch;

            if (!isBatch)
            {
                //var result = Server.PluginManager.PluginPacketHandler(package, false, Player);
                //if (result != package) package.PutPool();
                //package = result;

                //if (package == null) return;
            }

            Server.SendPackage(this, package);
            //lock (_queueSync)
            //{
            //	_sendQueueNotConcurrent.Enqueue(package);
            //}
        }
Example #2
0
 public virtual Player CreatePlayer(MiNetServer server, IPEndPoint endPoint)
 {
     var player = new Player(server, endPoint);
     player.MaxViewDistance = Config.GetProperty("MaxViewDistance", 22);
     OnPlayerCreated(new PlayerEventArgs(player));
     return player;
 }
Example #3
0
        public virtual void HandleMcpeLogin(McpeLogin message)
        {
            // Only one login!
            lock (_loginSyncLock)
            {
                if (_session.Username != null)
                {
                    Log.Info($"Player {_session.Username} doing multiple logins");
                    return;                     // Already doing login
                }

                _session.Username = string.Empty;
            }

            _playerInfo.ProtocolVersion = message.protocolVersion;

            if (MiNetServer.IsRunningOnMono())
            {
                DecodeCertMono(message);
            }
            else
            {
                DecodeCert(message);
            }
        }
Example #4
0
        public virtual Player CreatePlayer(MiNetServer server, IPEndPoint endPoint)
        {
            var player = new Player(server, endPoint);

            OnPlayerCreated(new PlayerEventArgs(player));
            return(player);
        }
Example #5
0
        public void SendPackage(Package package)
        {
            if (package == null)
            {
                return;
            }

            if (State == ConnectionState.Unconnected)
            {
                package.PutPool();
                return;
            }

            MiNetServer.TraceSend(package);

            bool isBatch = package is McpeWrapper;

            if (!isBatch)
            {
                //var result = Server.PluginManager.PluginPacketHandler(package, false, Player);
                //if (result != package) package.PutPool();
                //package = result;

                //if (package == null) return;
            }

            lock (_queueSync)
            {
                _sendQueueNotConcurrent.Enqueue(package);
                SignalTick();
            }
        }
Example #6
0
 public GreylistManager(MiNetServer server)
 {
     //_blacklist.Add(IPAddress.Parse("166.176.186.43"));
     //_blacklist.Add(IPAddress.Parse("185.89.216.247"));
     //_blacklist.Add(IPAddress.Parse("66.176.197.86"));
     //_blacklist.Add(IPAddress.Parse("78.197.138.50"));
     _server = server;
 }
Example #7
0
 public GreylistManager(MiNetServer server)
 {
     _blacklist.Add(IPAddress.Parse("86.126.166.61"));
     //_blacklist.Add(IPAddress.Parse("185.89.216.247"));
     //_blacklist.Add(IPAddress.Parse("66.176.197.86"));
     //_blacklist.Add(IPAddress.Parse("78.197.138.50"));
     _server = server;
 }
Example #8
0
        public virtual Player CreatePlayer(MiNetServer server, IPEndPoint endPoint)
        {
            var player = new Player(server, endPoint);

            player.MaxViewDistance = Config.GetProperty("MaxViewDistance", 22);
            OnPlayerCreated(new PlayerEventArgs(player));
            return(player);
        }
Example #9
0
        public PlayerNetworkSession(MiNetServer server, Player player, IPEndPoint endPoint, short mtuSize)
        {
            State = ConnectionState.Unconnected;

            Server         = server;
            MessageHandler = player;
            EndPoint       = endPoint;
            MtuSize        = mtuSize;

            _cancellationToken        = new CancellationTokenSource();
            _tickerHighPrecisionTimer = new HighPrecisionTimer(10, SendTick, true);
        }
Example #10
0
        public Player(MiNetServer server, IPEndPoint endPoint, Level level, int mtuSize)
            : base(-1, level)
        {
            Rtt = 300;
            Width = 0.6;
            Length = 0.6;
            Height = 1.80;

            Popups = new List<Popup>();

            Server = server;
            EndPoint = endPoint;
            _mtuSize = mtuSize;
            Level = level;

            Permissions = new PermissionManager(UserGroup.User);
            Permissions.AddPermission("*"); //All users can use all commands. (For debugging purposes)

            Inventory = new PlayerInventory(this);

            _chunksUsed = new Dictionary<Tuple<int, int>, McpeBatch>();

            IsSpawned = false;
            IsConnected = true;

            SpawnPosition = Level.SpawnPoint;
            KnownPosition = new PlayerLocation
            {
                X = SpawnPosition.X,
                Y = SpawnPosition.Y,
                Z = SpawnPosition.Z,
                Yaw = 91,
                Pitch = 28,
                HeadYaw = 91
            };

            GameMode = level.GameMode;

            _sendTicker = new Timer(SendQueue, null, 10, 10); // RakNet send tick-time
        }
Example #11
0
		public Player(MiNetServer server, IPEndPoint endPoint, int mtuSize) : base(-1, null)
		{
			Rtt = 300;
			Width = 0.6;
			Length = 0.6;
			Height = 1.80;

			Popups = new List<Popup>();
			Effects = new ConcurrentDictionary<EffectType, Effect>();

			Server = server;
			EndPoint = endPoint;
			_mtuSize = mtuSize;

			Inventory = new PlayerInventory(this);

			_chunksUsed = new Dictionary<Tuple<int, int>, McpeBatch>();

			IsSpawned = false;
			IsConnected = endPoint != null; // Can't connect if there is no endpoint

			if (IsConnected) _sendTicker = new Timer(SendQueue, null, 10, 10); // RakNet send tick-time
		}
Example #12
0
        public Player(MiNetServer server, IPEndPoint endPoint, Level level, PluginManager pluginManager, int mtuSize) : base(-1, level)
        {
            Rtt    = -1;
            Width  = 0.6;
            Length = 0.6;
            Height = 1.80;

            Popups = new List <Popup>();

            Server         = server;
            EndPoint       = endPoint;
            _mtuSize       = mtuSize;
            Level          = level;
            _pluginManager = pluginManager;

            Permissions = new PermissionManager(UserGroup.User);
            Permissions.AddPermission("*");             //All users can use all commands. (For debugging purposes)

            Inventory = new PlayerInventory(this);

            _chunksUsed = new Dictionary <Tuple <int, int>, ChunkColumn>();

            IsSpawned   = false;
            IsConnected = true;

            KnownPosition = new PlayerLocation
            {
                X       = Level.SpawnPoint.X,
                Y       = Level.SpawnPoint.Y,
                Z       = Level.SpawnPoint.Z,
                Yaw     = 91,
                Pitch   = 28,
                HeadYaw = 91
            };

            _sendTicker = new Timer(SendQueue, null, 10, 10);             // RakNet send tick-time
        }
Example #13
0
 public GreylistManager(MiNetServer server)
 {
     _server = server;
 }
Example #14
0
        private static void ProcessMessage(MiNetServer server, ReadOnlyMemory <byte> receivedBytes, IPEndPoint clientEndpoint)
        {
            var header = new DatagramHeader(receivedBytes.Span[0]);

            if (!header.IsValid)
            {
                // We parse as an offline message. This is not actually correct, but works.

                byte messageId = receivedBytes.Span[0];

                if (messageId <= (byte)DefaultMessageIdTypes.ID_USER_PACKET_ENUM)
                {
                    RakNetProcessor.HandleOfflineRakMessage(server, receivedBytes, clientEndpoint, messageId, server.ServerInfo);
                }
                else
                {
                    Log.Warn($"Receive invalid message, but not a RakNet message. Message ID={messageId}. Ignoring.");
                }

                return;
            }

            if (!server._rakNetSessions.TryGetValue(clientEndpoint, out RakSession rakNetSession))
            {
                //Log.DebugFormat("Receive MCPE message 0x{1:x2} without session {0}", senderEndpoint.Address, msgId);
                //if (!_badPacketBans.ContainsKey(senderEndpoint.Address))
                //{
                //	_badPacketBans.Add(senderEndpoint.Address, true);
                //}
                return;
            }

            if (rakNetSession.MessageHandler == null)
            {
                Log.ErrorFormat("Receive online message without message handler for IP={0}. Session removed.", clientEndpoint.Address);
                server._rakNetSessions.TryRemove(clientEndpoint, out rakNetSession);
                //if (!_badPacketBans.ContainsKey(senderEndpoint.Address))
                //{
                //	_badPacketBans.Add(senderEndpoint.Address, true);
                //}
                return;
            }

            if (rakNetSession.Evicted)
            {
                return;
            }

            rakNetSession.LastUpdatedTime = DateTime.UtcNow;

            if (header.IsAck)
            {
                rakNetSession.HandleAck(receivedBytes, server.ServerInfo);
                return;
            }

            if (header.IsNak)
            {
                rakNetSession.HandleNak(receivedBytes, server.ServerInfo);
                return;
            }

            var datagram = ConnectedPacket.CreateObject();

            try
            {
                datagram.Decode(receivedBytes);
            }
            catch (Exception e)
            {
                rakNetSession.Disconnect("Bad packet received from client.");

                Log.Warn($"Bad packet {receivedBytes.Span[0]}\n{Packet.HexDump(receivedBytes)}", e);

                server.GreylistManager.Blacklist(clientEndpoint.Address);

                return;
            }

            // IF reliable code below is enabled, useItem start sending doubles
            // for some unknown reason.

            //Reliability reliability = packet._reliability;
            //if (reliability == Reliability.Reliable
            //	|| reliability == Reliability.ReliableSequenced
            //	|| reliability == Reliability.ReliableOrdered
            //	)
            {
                server.EnqueueAck(rakNetSession, datagram.Header.DatagramSequenceNumber);
            }

            rakNetSession.HandleDatagram(datagram);
            datagram.PutPool();
        }
Example #15
0
 public GreylistManager(MiNetServer server)
 {
     _server = server;
 }
Example #16
0
        internal void HandlePacket(Packet message, PlayerNetworkSession playerSession)
        {
            //SignalTick();

            try
            {
                if (message == null)
                {
                    return;
                }

                if (typeof(UnknownPacket) == message.GetType())
                {
                    UnknownPacket packet = (UnknownPacket)message;
                    if (Log.IsDebugEnabled)
                    {
                        Log.Warn($"Received unknown packet 0x{message.Id:X2}\n{Packet.HexDump(packet.Message)}");
                    }

                    message.PutPool();
                    return;
                }

                if (typeof(McpeWrapper) == message.GetType())
                {
                    McpeWrapper batch    = (McpeWrapper)message;
                    var         messages = new List <Packet>();

                    // Get bytes
                    byte[] payload = batch.payload;
                    if (playerSession.CryptoContext != null && playerSession.CryptoContext.UseEncryption)
                    {
                        payload = CryptoUtils.Decrypt(payload, playerSession.CryptoContext);
                    }


                    // Decompress bytes

                    MemoryStream stream = new MemoryStream(payload);
                    if (stream.ReadByte() != 0x78)
                    {
                        if (Log.IsDebugEnabled)
                        {
                            Log.Error($"Incorrect ZLib header. Expected 0x78 0x9C 0x{message.Id:X2}\n{Packet.HexDump(batch.payload)}");
                        }
                        if (Log.IsDebugEnabled)
                        {
                            Log.Error($"Incorrect ZLib header. Decrypted 0x{message.Id:X2}\n{Packet.HexDump(payload)}");
                        }
                        throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                    }
                    stream.ReadByte();
                    using (var deflateStream = new DeflateStream(stream, CompressionMode.Decompress, false))
                    {
                        // Get actual packet out of bytes
                        using (MemoryStream destination = MiNetServer.MemoryStreamManager.GetStream())
                        {
                            deflateStream.CopyTo(destination);
                            destination.Position = 0;

                            while (destination.Position < destination.Length)
                            {
                                int  len = (int)VarInt.ReadUInt32(destination);
                                long pos = destination.Position;
                                int  id  = (int)VarInt.ReadUInt32(destination);
                                len = (int)(len - (destination.Position - pos));                                  // calculate len of buffer after varint
                                byte[] internalBuffer = new byte[len];
                                destination.Read(internalBuffer, 0, len);

                                //if (Log.IsDebugEnabled)
                                //	Log.Debug($"0x{internalBuffer[0]:x2}\n{Packet.HexDump(internalBuffer)}");

                                try
                                {
                                    messages.Add(PacketFactory.Create((byte)id, internalBuffer, "mcpe") ??
                                                 new UnknownPacket((byte)id, internalBuffer));
                                }
                                catch (Exception e)
                                {
                                    if (Log.IsDebugEnabled)
                                    {
                                        Log.Warn($"Error parsing packet 0x{message.Id:X2}\n{Packet.HexDump(internalBuffer)}");
                                    }

                                    throw;
                                }
                            }

                            if (destination.Length > destination.Position)
                            {
                                throw new Exception("Have more data");
                            }
                        }
                    }
                    foreach (var msg in messages)
                    {
                        // Temp fix for performance, take 1.
                        var interact = msg as McpeInteract;
                        if (interact?.actionId == 4 && interact.targetRuntimeEntityId == 0)
                        {
                            continue;
                        }

                        msg.DatagramSequenceNumber = batch.DatagramSequenceNumber;
                        msg.Reliability            = batch.Reliability;
                        msg.ReliableMessageNumber  = batch.ReliableMessageNumber;
                        msg.OrderingChannel        = batch.OrderingChannel;
                        msg.OrderingIndex          = batch.OrderingIndex;
                        HandlePacket(msg, playerSession);
                    }

                    message.PutPool();
                    return;
                }

                MiNetServer.TraceReceive(message);

                if (CryptoContext != null && CryptoContext.UseEncryption)
                {
                    MiNetServer.FastThreadPool.QueueUserWorkItem(() =>
                    {
                        HandlePacket(MessageHandler, message as Packet);
                        message.PutPool();
                    });
                }
                else
                {
                    HandlePacket(MessageHandler, message);
                    message.PutPool();
                }
            }
            catch (Exception e)
            {
                Log.Error("Packet handling", e);
                throw;
            }
        }
Example #17
0
		public virtual Player CreatePlayer(MiNetServer server, IPEndPoint endPoint, int mtuSize)
		{
			return new Player(server, endPoint, mtuSize);
		}
Example #18
0
 public virtual Player CreatePlayer(MiNetServer server, IPEndPoint endPoint, int mtuSize)
 {
     return(new Player(server, endPoint, mtuSize));
 }
Example #19
0
 public DefaultServerManager(MiNetServer miNetServer)
 {
     _miNetServer = miNetServer;
     _getServer   = new DefaultServer(miNetServer);
 }
Example #20
0
        internal void HandlePackage(Package message, PlayerNetworkSession playerSession)
        {
            //SignalTick();

            try
            {
                if (message == null)
                {
                    return;
                }

                if (typeof(UnknownPackage) == message.GetType())
                {
                    UnknownPackage packet = (UnknownPackage)message;
                    if (Log.IsDebugEnabled)
                    {
                        Log.Warn($"Received unknown package 0x{message.Id:X2}\n{Package.HexDump(packet.Message)}");
                    }

                    message.PutPool();
                    return;
                }

                if (typeof(McpeWrapper) == message.GetType())
                {
                    McpeWrapper batch    = (McpeWrapper)message;
                    var         messages = new List <Package>();

                    // Get bytes
                    byte[] payload = batch.payload;
                    if (playerSession.CryptoContext != null && playerSession.CryptoContext.UseEncryption)
                    {
                        throw new Exception("No crypto enabled");
                    }

                    // Decompress bytes

                    MemoryStream stream = new MemoryStream(payload);
                    if (stream.ReadByte() != 0x78)
                    {
                        throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                    }
                    stream.ReadByte();
                    using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                    {
                        // Get actual package out of bytes
                        using (MemoryStream destination = MiNetServer.MemoryStreamManager.GetStream())
                        {
                            defStream2.CopyTo(destination);
                            destination.Position = 0;
                            NbtBinaryReader reader = new NbtBinaryReader(destination, true);

                            while (destination.Position < destination.Length)
                            {
                                //int len = reader.ReadInt32();
                                int    len            = BatchUtils.ReadLength(destination);
                                byte[] internalBuffer = reader.ReadBytes(len);

                                //if (Log.IsDebugEnabled)
                                //	Log.Debug($"0x{internalBuffer[0]:x2}\n{Package.HexDump(internalBuffer)}");

                                messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer, "mcpe") ??
                                             new UnknownPackage(internalBuffer[0], internalBuffer));
                            }

                            if (destination.Length > destination.Position)
                            {
                                throw new Exception("Have more data");
                            }
                        }
                    }
                    foreach (var msg in messages)
                    {
                        // Temp fix for performance, take 1.
                        var interact = msg as McpeInteract;
                        if (interact?.actionId == 4 && interact.targetRuntimeEntityId == 0)
                        {
                            continue;
                        }

                        msg.DatagramSequenceNumber = batch.DatagramSequenceNumber;
                        msg.Reliability            = batch.Reliability;
                        msg.ReliableMessageNumber  = batch.ReliableMessageNumber;
                        msg.OrderingChannel        = batch.OrderingChannel;
                        msg.OrderingIndex          = batch.OrderingIndex;
                        HandlePackage(msg, playerSession);
                    }

                    message.PutPool();
                    return;
                }

                MiNetServer.TraceReceive(message);

                if (CryptoContext != null && CryptoContext.UseEncryption)
                {
                    MiNetServer.FastThreadPool.QueueUserWorkItem(delegate()
                    {
                        HandlePackage(MessageHandler, message as Package);
                        message.PutPool();
                    });
                }
                else
                {
                    HandlePackage(MessageHandler, message);
                    message.PutPool();
                }
            }
            catch (Exception e)
            {
                Log.Error("Package handling", e);
                throw;
            }
        }
        internal void HandlePackage(Package message, PlayerNetworkSession playerSession)
        {
            if (message == null)
            {
                return;
            }

            if (typeof(McpeWrapper) == message.GetType())
            {
                McpeWrapper wrapper = (McpeWrapper)message;

                // Get bytes
                byte[] payload = wrapper.payload;
                if (playerSession.CryptoContext != null && playerSession.CryptoContext.UseEncryption)
                {
                    payload = CryptoUtils.Decrypt(payload, playerSession.CryptoContext);
                }

                //if (Log.IsDebugEnabled)
                //	Log.Debug($"0x{payload[0]:x2}\n{Package.HexDump(payload)}");

                var msg = PackageFactory.CreatePackage(payload[0], payload, "mcpe") ?? new UnknownPackage(payload[0], payload);
                msg.DatagramSequenceNumber = wrapper.DatagramSequenceNumber;
                msg.Reliability            = wrapper.Reliability;
                msg.ReliableMessageNumber  = wrapper.ReliableMessageNumber;
                msg.OrderingChannel        = wrapper.OrderingChannel;
                msg.OrderingIndex          = wrapper.OrderingIndex;
                HandlePackage(msg, playerSession);

                message.PutPool();
                return;
            }

            if (typeof(UnknownPackage) == message.GetType())
            {
                UnknownPackage packet = (UnknownPackage)message;
                if (Log.IsDebugEnabled)
                {
                    Log.Warn($"Received unknown package 0x{message.Id:X2}\n{Package.HexDump(packet.Message)}");
                }

                message.PutPool();
                return;
            }

            if (typeof(McpeBatch) == message.GetType())
            {
                Log.Debug("Handle MCPE batch message");
                McpeBatch batch = (McpeBatch)message;

                var messages = new List <Package>();

                // Get bytes
                byte[] payload = batch.payload.Array;
                // Decompress bytes

                MemoryStream stream = new MemoryStream(payload);
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                }
                stream.ReadByte();
                using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                {
                    // Get actual package out of bytes
                    MemoryStream destination = MiNetServer.MemoryStreamManager.GetStream();
                    defStream2.CopyTo(destination);
                    destination.Position = 0;
                    NbtBinaryReader reader = new NbtBinaryReader(destination, true);

                    while (destination.Position < destination.Length)
                    {
                        int    len            = reader.ReadInt32();
                        byte[] internalBuffer = reader.ReadBytes(len);

                        //if (Log.IsDebugEnabled)
                        //	Log.Debug($"0x{internalBuffer[0]:x2}\n{Package.HexDump(internalBuffer)}");

                        messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer, "mcpe") ?? new UnknownPackage(internalBuffer[0], internalBuffer));
                    }

                    if (destination.Length > destination.Position)
                    {
                        throw new Exception("Have more data");
                    }
                }
                foreach (var msg in messages)
                {
                    msg.DatagramSequenceNumber = batch.DatagramSequenceNumber;
                    msg.Reliability            = batch.Reliability;
                    msg.ReliableMessageNumber  = batch.ReliableMessageNumber;
                    msg.OrderingChannel        = batch.OrderingChannel;
                    msg.OrderingIndex          = batch.OrderingIndex;
                    HandlePackage(msg, playerSession);
                }

                message.PutPool();
                return;
            }

            MiNetServer.TraceReceive(message, message.OrderingIndex);

            if (CryptoContext != null && CryptoContext.UseEncryption)
            {
                MiNetServer.FastThreadPool.QueueUserWorkItem(delegate()
                {
                    HandlePackage(MessageHandler, message as Package);
                    message.PutPool();
                });
            }
            else
            {
                HandlePackage(MessageHandler, message);
                message.PutPool();
            }
        }
Example #22
0
 public DefaultServer(MiNetServer server)
 {
     _server = server;
 }
Example #23
0
		public void Configure(MiNetServer server)
		{
			BlockFactory.CustomBlockFactory = new PluginBlockFactory(new GameManager());
		}
Example #24
0
 public DefaultServer(MiNetServer server)
 {
     _server = server;
 }
Example #25
0
 public DefualtServerManager(MiNetServer miNetServer)
 {
     _miNetServer = miNetServer;
     _getServer = new DefaultServer(miNetServer);
 }