public async Task <RakNetPacket> ReceivePacketAsync()
        {
            UdpReceiveResult result = await ReceiveAsync();

            byte[]       buffer = result.Buffer;
            RakNetPacket packet = PacketIdentifier.GetPacketFormId(buffer[0]);

            packet.SetBuffer(buffer);
            packet.EndPoint = result.RemoteEndPoint;
            DownloadBytes  += (uint)result.Buffer.Length;

            try
            {
                packet.DecodeHeader();
                packet.DecodePayload();
            }
            catch (Exception e)
            {
                throw new PacketDecodeException(e.Message, e);
            }

            new SocketPacketReceiveEventArgs(this, packet, DownloadBytes)
            .Invoke(this, ReceivePacketEvent);

            return(packet);
        }
Exemple #2
0
        private void HandleRakNetPacket(IPEndPoint endPoint, byte[] bytes)
        {
            if (bytes?.Length != 0)
            {
                byte         msgId = bytes[0];
                RakNetPacket pk    = this.GetRakNetPacket(msgId, bytes);
                if (pk != null)
                {
                    RakNetPacketReceiveEventArgs ev = new RakNetPacketReceiveEventArgs(endPoint, pk);
                    Server.Instance.Event.Network.OnRakNetPacketReceive(this, ev);

                    if (ev.IsCancel)
                    {
                        return;
                    }

                    pk = ev.Packet;

                    if (pk is OfflineMessage)
                    {
                        if (this.SessionCreated(endPoint))
                        {
                            Logger.Debug("%server.network.raknet.sessionCreated", endPoint);
                            return;
                        }

                        this.HandleOfflineMessage(endPoint, (OfflineMessage)pk);
                        pk.Dispose();
                        return;
                    }

                    if (!this.SessionCreated(endPoint))
                    {
                        Logger.Debug("%server.network.raknet.sessionNotCreated", endPoint);
                        return;
                    }

                    if (pk is DataPacket)
                    {
                        NetworkSession session = this.GetSession(endPoint);
                        session.HandleDataPacket((DataPacket)pk);
                        pk.Dispose();
                        return;
                    }

                    if (pk is AcknowledgePacket)
                    {
                        NetworkSession session = this.GetSession(endPoint);
                        session.HandleAcknowledgePacket((AcknowledgePacket)pk);
                        pk.Dispose();
                        return;
                    }
                }

                if (Server.Instance.Config.PacketDebug)
                {
                    Logger.Debug("%server.network.raknet.notHandle", msgId.ToString("X"));
                }
            }
        }
        public RakNetPacket ReceivePacket()
        {
            IPEndPoint endPoint = null;

            byte[]       buffer = Receive(ref endPoint);
            RakNetPacket packet = PacketIdentifier.GetPacketFormId(buffer[0]);

            packet.SetBuffer(buffer);
            packet.EndPoint = endPoint;
            DownloadBytes  += (uint)buffer.Length;

            try
            {
                packet.DecodeHeader();
                packet.DecodePayload();
            }
            catch (Exception e)
            {
                throw new PacketDecodeException(e.Message, e);
            }

            new SocketPacketReceiveEventArgs(this, packet, DownloadBytes)
            .Invoke(this, ReceivePacketEvent);

            return(packet);
        }
Exemple #4
0
        public async Task Send(UdpConnection Client, params RakPacket[] packets)
        {
            var rakPacket = RakNetPacket.Create(Client.Sequence);

            Client.Sequence = Client.Sequence.Add(1);
            rakPacket.Enclosing.AddRange(packets);
            var data = rakPacket.Serialize();
            await UdpServer.SendAsync(data, data.Length, Client.EndPoint);
        }
        public override void HandlePeerPacket(RakNetPacket packet)
        {
            base.HandlePeerPacket(packet);

            if (packet is CustomPacket customPacket)
            {
                HandleCustomHandle(customPacket);
            }
        }
Exemple #6
0
        public override void HandleRakNetPacket(RakNetPacket packet)
        {
            base.HandleRakNetPacket(packet);

            if (packet is CustomPacket customPacket && IsConnected(packet.EndPoint))
            {
                IPEndPoint    endPoint = packet.EndPoint;
                MinecraftPeer peer     = GetPeer <MinecraftPeer>(endPoint);
                peer.HandlePeerPacket(customPacket);
            }
Exemple #7
0
        public void StartRakNetClient()
        {
            RakNetSocket socket = RakNet.CreateClient(new IPEndPoint(IPAddress.Any, 19132));
            //client.OnReceive = packet => { Console.WriteLine(packet.ReadByte()); };
            RakNetPacket p = socket.ReceivePacketAsync().GetAwaiter().GetResult();

            if (p is UnconnectedPing unconnectedPing)
            {
                Console.WriteLine(p.PacketId);
                Console.WriteLine(unconnectedPing.TimeStamp);
                Console.WriteLine(unconnectedPing.PingId);
            }
        }
Exemple #8
0
        public RakNetPacket GetRakNetPacket(int msgId, byte[] buffer = null)
        {
            RakNetPacket pk = null;

            MineNET_Registries.RakNetPacket.TryGetValue(msgId, out pk);
            pk = pk?.Clone();

            if (pk != null && buffer != null)
            {
                pk.SetBuffer(buffer);
                pk.Decode();
            }

            return(pk);
        }
Exemple #9
0
        public void Send(IPEndPoint point, RakNetPacket msg)
        {
            msg.Encode();

            RakNetPacketSendEventArgs ev = new RakNetPacketSendEventArgs(point, msg);

            Server.Instance.Event.Network.OnRakNetPacketSend(this, ev);

            if (ev.IsCancel)
            {
                return;
            }

            msg = ev.Packet;

            byte[] buffer = msg.ToArray();
            this.Client.Send(buffer, buffer.Length, point);
        }
Exemple #10
0
        public async void SendPacketAsync(RakNetPacket packet)
        {
            try
            {
                packet.EncodeHeader();
                packet.EncodePayload();
            }
            catch (Exception e)
            {
                throw new PacketEncodeException(e.Message, e);
            }

            byte[] buf = packet.GetBuffer();
            UploadBytes += (ulong) await SendAsync(buf, buf.Length, packet.EndPoint);

            new SocketPacketSendEventArgs(this, packet, UploadBytes)
            .Invoke(this, SendPacketEvent);

            packet.Close();
        }
        public void HandleConnectedPacket(EncapsulatedPacket packet)
        {
            byte[]       buffer = packet.Payload;
            RakNetPacket pk     = Server.Socket.PacketIdentifier.GetPacketFormId(buffer[0]);

            pk.EndPoint = PeerEndPoint;
            pk.SetBuffer(buffer);

            pk.DecodeHeader();
            pk.DecodePayload();

            if (pk is ConnectionRequest connectionRequest && State == RakNetPeerState.Connected)
            {
                ConnectionRequestAccepted accepted = new ConnectionRequestAccepted();
                accepted.PeerAddress     = PeerEndPoint;
                accepted.ClientTimestamp = connectionRequest.Timestamp;
                accepted.ServerTimestamp = TimeSpan.FromMilliseconds(Environment.TickCount);
                accepted.EndPoint        = PeerEndPoint;
                SendEncapsulatedPacket(accepted, Reliability.Unreliable, 0);

                State = RakNetPeerState.Handshaking;
            }
Exemple #12
0
        public void QueueConnectedPacket(RakNetPacket packet, int reliability, int orderChannel,
                                         int flags = RakNetProtocol.FlagNormal)
        {
            packet.Encode();

            EncapsulatedPacket pk = new EncapsulatedPacket();

            pk.Reliability  = reliability;
            pk.OrderChannel = orderChannel;
            pk.Buffer       = packet.ToArray();

            RakNetEncapsulatedSendEventArgs ev = new RakNetEncapsulatedSendEventArgs(this, pk);

            Server.Instance.Event.Network.OnRakNetEncapsulatedSend(this, ev);

            if (ev.IsCancel)
            {
                return;
            }

            pk = ev.Packet;

            this.AddEncapsulatedToQueue(pk, flags);
        }
Exemple #13
0
        public void HandleEncapsulatedPacketRoute(EncapsulatedPacket packet)
        {
            if (this.Manager == null)
            {
                return;
            }

            int          id = packet.Buffer[0];
            RakNetPacket pk = this.Manager.GetRakNetPacket(id, packet.Buffer);

            if (pk != null)
            {
                if (id < 0x86)
                {
                    if (this.State == SessionState.Connecting)
                    {
                        if (id == RakNetProtocol.ClientConnectDataPacket)
                        {
                            ClientConnectDataPacket   ccd = (ClientConnectDataPacket)pk;
                            ServerHandShakeDataPacket shd = new ServerHandShakeDataPacket();
                            shd.EndPoint = this.EndPoint;
                            shd.SendPing = ccd.SendPing;
                            shd.SendPong = ccd.SendPing + 1000;

                            this.QueueConnectedPacket(shd, RakNetPacketReliability.UNRELIABLE, -1,
                                                      RakNetProtocol.FlagImmediate);
                        }
                        else if (id == RakNetProtocol.ClientHandShakeDataPacket)
                        {
                            ClientHandShakeDataPacket chsd = (ClientHandShakeDataPacket)pk;

                            if (chsd.EndPoint.Port == Server.Instance.EndPoint.Port)
                            {
                                this.State = SessionState.Connected;
                            }
                        }
                    }
                    else if (id == RakNetProtocol.ClientDisconnectDataPacket)
                    {
                        this.Disconnect("clientDisconnect");
                    }
                    else if (id == RakNetProtocol.OnlinePing)
                    {
                        OnlinePing ping = (OnlinePing)pk;
                        OnlinePong pong = new OnlinePong();
                        pong.PingID = ping.PingID;

                        this.LastPingTime = SendPingTime;

                        this.QueueConnectedPacket(pong, RakNetPacketReliability.UNRELIABLE, -1,
                                                  RakNetProtocol.FlagImmediate);
                    }
                    else if (id == RakNetProtocol.OnlinePong)
                    {
                    }
                }
                else if (this.State == SessionState.Connected)
                {
                    if (id == RakNetProtocol.BatchPacket)
                    {
                        this.HandleBatchPacket((BatchPacket)pk);
                    }
                }
            }
        }
Exemple #14
0
 public void SendPacket(RakNetPacket packet)
 {
     Server.Socket.SendPacket(packet);
 }
Exemple #15
0
 public PeerHandlePacketEventArgs(RakNetPeer peer, RakNetPacket packet) : base(peer)
 {
     Packet = packet;
 }
Exemple #16
0
 public RakNetPacketSendEventArgs(IPEndPoint endPoint, RakNetPacket packet)
 {
     this.EndPoint = endPoint;
     this.Packet   = packet;
 }
Exemple #17
0
 public virtual void HandlePeerPacket(RakNetPacket packet)
 {
     new PeerHandlePacketEventArgs(this, packet)
     .Invoke(this, PeerHandlePacketEvent);
 }
 public SocketPacketSendEventArgs(RakNetSocket socket, RakNetPacket packet, ulong bytes) : base(socket)
 {
     SendPacket = packet;
     SendBytes  = bytes;
 }
Exemple #19
0
 public virtual void HandleRakNetPacket(RakNetPacket packet)
 {
     new ServerPacketHandleEventArgs(this, packet)
     .Invoke(this, PacketHandleEvent);
 }
 public ServerPacketHandleEventArgs(RakNetServer server, RakNetPacket packet) : base(server)
 {
     Packet = packet;
 }
Exemple #21
0
        async Task HandleRakNetPacket(RakNetPacket rakPacket, IPEndPoint endpoint)
        {
            if (!Clients.ContainsKey(endpoint))
            {
                return;
            }

            var Client = Clients[endpoint];

            Client.LastUpdate = DateTime.Now;
            if (!rakPacket.IsACKorNAK)
            {
                Client.Sequence = rakPacket.SequenceNumber;
            }

            foreach (var enclosing in rakPacket.Enclosing)
            {
                switch (enclosing.MessageID)
                {
                case RakPacketType.ConnectedPong: {
                    Console.WriteLine("[<=] PONG!");
                    break;
                }

                case RakPacketType.ConnectedPing: { await Send(Client, ConnectedPongPacket.FromPing(enclosing.Get <ConnectedPingPacket>(), StartTime)); break; }

                case RakPacketType.ConnectionRequest: {
                    var request = enclosing.Get <ConnectionRequestPacket>();
                    Client.Player     = new Player();
                    Client.Player.CID = request.ClientGuid;
                    await Send(Client, ConnectionRequestAcceptedPacket.FromRequest(request, endpoint));

                    break;
                }

                case RakPacketType.LoginRequest: {
                    var request = enclosing.Get <LoginRequestPacket>();
                    var status  = request.StatusFor(14);

                    Client.Player.Username = request.Username;
                    if (Client.Player.Username == "server" ||            // Don't impersonate the server.
                        World.GetPlayerByName(request.Username) != null) // Don't log in if there's a player already in game.
                    {
                        await Send(Client, LoginResponsePacket.FromRequest(request, Status.ClientOutdated));

                        break;
                    }

                    // StartGame is when the Client gets it's own EntityID.
                    Client.Player.EID = World.LastEID++;

                    //TODO(atipls): More checks, check if a the player name is already logged in.
                    await Send(Client, LoginResponsePacket.FromRequest(request, status),
                               status == Status.VersionsMatch?new StartGamePacket(request.ReliableNum.IntValue, Client.Player.EID) : null
                               );

                    await World.AddPlayer(Client);

                    Console.WriteLine("Players:");
                    foreach (var player in World.Players)
                    {
                        Console.WriteLine($"{{ EID: {player.Player.EID} CID: {player.Player.CID} Name: {player.Player.Username} }}");
                    }

                    break;
                }

                case RakPacketType.Ready: {
                    // Notify the new client about existing players.
                    foreach (var P in World.Players)
                    {
                        if (P == Client)
                        {
                            continue;
                        }
                        await Send(Client, new AddPlayerPacket(P.Player));
                    }
                    break;
                }

                case RakPacketType.NewIncomingConnection: {
                    Console.WriteLine($"[ +] {endpoint}");
                    break;
                }

                case RakPacketType.Message: {
                    await SendToEveryone(enclosing.Get <MessagePacket>());

                    break;
                }

                case RakPacketType.MovePlayer: {
                    var packet = enclosing.Get <MovePlayerPacket>();
                    Console.WriteLine($"MovePlayer: {{ ID: {packet.ID} (== {Client.Player.EID} OR == {Client.Player.CID}) }}");
                    await World.MovePlayer(Client, packet.Position, packet.Pitch, packet.Yaw);

                    break;
                }

                case RakPacketType.PlayerDisconnect: {
                    // Let the client updater thread disconnect the player.
                    Client.ForceInvalidate = true;
                    break;
                }

                default:
                    Console.WriteLine($"Unhandled RakPacket: {enclosing.MessageID}");
                    break;
                }
            }

            if (!rakPacket.IsACKorNAK)
            {
                var ackPacket = rakPacket.CreateACK();
                var ackData   = ackPacket.Serialize();
                await UdpServer.SendAsync(ackData, ackData.Length, endpoint);
            }
        }
Exemple #22
0
 public void SendPacket(RakNetPacket pk)
 {
     this.Manager?.Send(this.EndPoint, pk);
 }
 public SocketPacketReceiveEventArgs(RakNetSocket socket, RakNetPacket packet, ulong bytes) : base(socket)
 {
     ReceivePacket = packet;
     ReceiveBytes  = bytes;
 }