public override void Start(int rate)
        {
            base.Start(rate);

            window = new GameWindow();
            window.Visible = true;

            Uri shader = new Uri("shader://FileSystemMod/effects/basic30.effect");
            renderer = new GL30BatchVertexRenderer();
            /*
            renderer.ActiveShader = sh;
            renderer.ActiveShader["Proj"] = Matrix4.Identity;
            renderer.ActiveShader["View"] = Matrix4.Identity;
            */
            window.KeyPress += new EventHandler<KeyPressEventArgs>(window_KeyPress);

            int port = 2861;

            Util.Msg("Starting Client");
            NetPeerConfiguration config = new NetPeerConfiguration(Watertight.ImplName + Watertight.Version);
            config.Port = port + 1;
            config.UseMessageRecycling = true;

            NetClient client = new NetClient(config);
            client.Start();

            NetOutgoingMessage connectMessage = client.CreateMessage();
            ConnectPacket connect = new ConnectPacket();
            connect.Encode(ref connectMessage);

            client.Connect("localhost", port, connectMessage);

            Simulation.LuaComponent lc = Simulation.EntityComponentDictionary.NewComponent("TestLuaComponent") as Simulation.LuaComponent;

            foreach (Mod m in ModManager.Mods())
            {
                m.ResourceLoad();
            }

            RunGameLoop();
        }
Ejemplo n.º 2
0
        Packet DecodePacketInternal(IByteBuffer buffer, int packetSignature, ref int remainingLength, IChannelHandlerContext context)
        {
            if (Signatures.IsPublish(packetSignature))
            {
                var qualityOfService = (QualityOfService)((packetSignature >> 1) & 0x3); // take bits #1 and #2 ONLY and convert them into QoS value
                if (qualityOfService == QualityOfService.Reserved)
                {
                    ThrowHelper.ThrowDecoderException_UnexpectedQoSValueForPublish(qualityOfService);
                }

                bool duplicate = (packetSignature & 0x8) == 0x8; // test bit#3
                bool retain    = (packetSignature & 0x1) != 0;   // test bit#0
                var  packet    = new PublishPacket(qualityOfService, duplicate, retain);
                DecodePublishPacket(buffer, packet, ref remainingLength);
                return(packet);
            }

            switch (packetSignature) // strict match checks for valid message type + correct values in flags part
            {
            case Signatures.PubAck:
                var pubAckPacket = new PubAckPacket();
                DecodePacketIdVariableHeader(buffer, pubAckPacket, ref remainingLength);
                return(pubAckPacket);

            case Signatures.PubRec:
                var pubRecPacket = new PubRecPacket();
                DecodePacketIdVariableHeader(buffer, pubRecPacket, ref remainingLength);
                return(pubRecPacket);

            case Signatures.PubRel:
                var pubRelPacket = new PubRelPacket();
                DecodePacketIdVariableHeader(buffer, pubRelPacket, ref remainingLength);
                return(pubRelPacket);

            case Signatures.PubComp:
                var pubCompPacket = new PubCompPacket();
                DecodePacketIdVariableHeader(buffer, pubCompPacket, ref remainingLength);
                return(pubCompPacket);

            case Signatures.PingReq:
                if (!_isServer)
                {
                    ValidateServerPacketExpected(packetSignature);
                }
                return(PingReqPacket.Instance);

            case Signatures.Subscribe:
                if (!_isServer)
                {
                    ValidateServerPacketExpected(packetSignature);
                }
                var subscribePacket = new SubscribePacket();
                DecodePacketIdVariableHeader(buffer, subscribePacket, ref remainingLength);
                DecodeSubscribePayload(buffer, subscribePacket, ref remainingLength);
                return(subscribePacket);

            case Signatures.Unsubscribe:
                if (!_isServer)
                {
                    ValidateServerPacketExpected(packetSignature);
                }
                var unsubscribePacket = new UnsubscribePacket();
                DecodePacketIdVariableHeader(buffer, unsubscribePacket, ref remainingLength);
                DecodeUnsubscribePayload(buffer, unsubscribePacket, ref remainingLength);
                return(unsubscribePacket);

            case Signatures.Connect:
                if (!_isServer)
                {
                    ValidateServerPacketExpected(packetSignature);
                }
                var connectPacket = new ConnectPacket();
                DecodeConnectPacket(buffer, connectPacket, ref remainingLength, context);
                return(connectPacket);

            case Signatures.Disconnect:
                if (!_isServer)
                {
                    ValidateServerPacketExpected(packetSignature);
                }
                return(DisconnectPacket.Instance);

            case Signatures.ConnAck:
                if (_isServer)
                {
                    ValidateClientPacketExpected(packetSignature);
                }
                var connAckPacket = new ConnAckPacket();
                DecodeConnAckPacket(buffer, connAckPacket, ref remainingLength);
                return(connAckPacket);

            case Signatures.SubAck:
                if (_isServer)
                {
                    ValidateClientPacketExpected(packetSignature);
                }
                var subAckPacket = new SubAckPacket();
                DecodePacketIdVariableHeader(buffer, subAckPacket, ref remainingLength);
                DecodeSubAckPayload(buffer, subAckPacket, ref remainingLength);
                return(subAckPacket);

            case Signatures.UnsubAck:
                if (_isServer)
                {
                    ValidateClientPacketExpected(packetSignature);
                }
                var unsubAckPacket = new UnsubAckPacket();
                DecodePacketIdVariableHeader(buffer, unsubAckPacket, ref remainingLength);
                return(unsubAckPacket);

            case Signatures.PingResp:
                if (_isServer)
                {
                    ValidateClientPacketExpected(packetSignature);
                }
                return(PingRespPacket.Instance);

            default:
                return(ThrowHelper.ThrowDecoderException_FirstPacketByteValueIsInvalid(packetSignature));
            }
        }
Ejemplo n.º 3
0
        static void DecodeConnectPacket(IByteBuffer buffer, ConnectPacket packet, ref int remainingLength, IChannelHandlerContext context)
        {
            string protocolName = DecodeString(buffer, ref remainingLength);

            if (!string.Equals(Util.ProtocolName, protocolName
#if NETCOREAPP_3_0_GREATER || NETSTANDARD_2_0_GREATER
                               ))
#else
                               , StringComparison.Ordinal))
#endif
            {
                ThrowHelper.ThrowDecoderException_UnexpectedProtocolName(protocolName);
            }
            packet.ProtocolName = Util.ProtocolName;

            DecreaseRemainingLength(ref remainingLength, 1);
            packet.ProtocolLevel = buffer.ReadByte();

            if (packet.ProtocolLevel != Util.ProtocolLevel)
            {
                var connAckPacket = new ConnAckPacket
                {
                    ReturnCode = ConnectReturnCode.RefusedUnacceptableProtocolVersion
                };
                context.WriteAndFlushAsync(connAckPacket);
                ThrowHelper.ThrowDecoderException_UnexpectedProtocolLevel(packet.ProtocolLevel);
            }

            DecreaseRemainingLength(ref remainingLength, 1);
            int connectFlags = buffer.ReadByte();

            packet.CleanSession = (connectFlags & 0x02) == 0x02;

            bool hasWill = (connectFlags & 0x04) == 0x04;
            if (hasWill)
            {
                packet.HasWill    = true;
                packet.WillRetain = (connectFlags & 0x20) == 0x20;
                var willQualityOfService = packet.WillQualityOfService = (QualityOfService)((connectFlags & 0x18) >> 3);
                if (willQualityOfService == QualityOfService.Reserved)
                {
                    ThrowHelper.ThrowDecoderException_UnexpectedWillQoSValueOf(willQualityOfService);
                }
                packet.WillTopicName = string.Empty;
            }
            else if ((connectFlags & 0x38) != 0) // bits 3,4,5 [MQTT-3.1.2-11]
            {
                ThrowHelper.ThrowDecoderException_MQTT_312_11();
            }

            packet.HasUsername = (connectFlags & 0x80) == 0x80;
            packet.HasPassword = (connectFlags & 0x40) == 0x40;
            if (packet.HasPassword && !packet.HasUsername)
            {
                ThrowHelper.ThrowDecoderException_MQTT_312_22();
            }
            if ((connectFlags & 0x1) != 0) // [MQTT-3.1.2-3]
            {
                ThrowHelper.ThrowDecoderException_MQTT_312_3();
            }

            packet.KeepAliveInSeconds = DecodeUnsignedShort(buffer, ref remainingLength);

            string clientId = DecodeString(buffer, ref remainingLength);
            if (clientId is null)
            {
                Util.ValidateClientId();
            }
            packet.ClientId = clientId;

            if (hasWill)
            {
                packet.WillTopicName = DecodeString(buffer, ref remainingLength);
                int willMessageLength = DecodeUnsignedShort(buffer, ref remainingLength);
                DecreaseRemainingLength(ref remainingLength, willMessageLength);
                packet.WillMessage = buffer.ReadBytes(willMessageLength);
            }

            if (packet.HasUsername)
            {
                packet.Username = DecodeString(buffer, ref remainingLength);
            }

            if (packet.HasPassword)
            {
                packet.Password = DecodeString(buffer, ref remainingLength);
            }
        }
Ejemplo n.º 4
0
 private bool v_DefaultAuth(ConnectPacket packet)
 {
     return(Network.ShouldAuthWhenDefault);
 }
        /// <summary>
        ///     Performs complete initialization of <see cref="MqttAdapter" /> based on received CONNECT packet.
        /// </summary>
        /// <param name="context"><see cref="IChannelHandlerContext" /> instance.</param>
        /// <param name="packet">CONNECT packet.</param>
        async void Connect(IChannelHandlerContext context, ConnectPacket packet)
        {
            bool connAckSent = false;

            Exception exception = null;

            try
            {
                if (!this.IsInState(StateFlags.WaitingForConnect))
                {
                    ShutdownOnError(context, ConnectProcessingScope, new InvalidOperationException("CONNECT has been received in current session already. Only one CONNECT is expected per session."));
                    return;
                }

                this.stateFlags = StateFlags.ProcessingConnect;
                this.identity   = await this.authProvider.GetAsync(packet.ClientId,
                                                                   packet.Username, packet.Password, context.Channel.RemoteAddress);

                if (!this.identity.IsAuthenticated)
                {
                    CommonEventSource.Log.Info("ClientNotAuthenticated", $"Client ID: {packet.ClientId}; Username: {packet.Username}", this.ChannelId);
                    connAckSent = true;
                    await Util.WriteMessageAsync(context, new ConnAckPacket
                    {
                        ReturnCode = ConnectReturnCode.RefusedNotAuthorized
                    });

                    PerformanceCounters.ConnectionFailedAuthPerSecond.Increment();
                    ShutdownOnError(context, ConnectProcessingScope, new AuthenticationException("Authentication failed."));
                    return;
                }

                CommonEventSource.Log.Info("ClientAuthenticated", this.identity.ToString(), this.ChannelId);

                this.messagingBridge = await this.messagingBridgeFactory(this.identity);

                bool sessionPresent = await this.EstablishSessionStateAsync(packet.CleanSession);

                this.keepAliveTimeout = this.DeriveKeepAliveTimeout(context, packet);

                if (packet.HasWill)
                {
                    var will = new PublishPacket(packet.WillQualityOfService, false, packet.WillRetain);
                    will.TopicName  = packet.WillTopicName;
                    will.Payload    = packet.WillMessage;
                    this.willPacket = will;
                }

                connAckSent = true;
                await Util.WriteMessageAsync(context, new ConnAckPacket
                {
                    SessionPresent = sessionPresent,
                    ReturnCode     = ConnectReturnCode.Accepted
                });

                this.CompleteConnect(context);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                if (!connAckSent)
                {
                    try
                    {
                        await Util.WriteMessageAsync(context, new ConnAckPacket
                        {
                            ReturnCode = ConnectReturnCode.RefusedServerUnavailable
                        });
                    }
                    catch (Exception ex)
                    {
                        if (CommonEventSource.Log.IsVerboseEnabled)
                        {
                            CommonEventSource.Log.Verbose("Error sending 'Server Unavailable' CONNACK.", ex.ToString(), this.ChannelId);
                        }
                    }
                }

                ShutdownOnError(context, ConnectProcessingScope, exception);
            }
        }
Ejemplo n.º 6
0
        public void ConnectPacket(string userName)
        {
            ConnectPacket packet = new ConnectPacket(userName + "#" + ID);

            SendPacket(packet);
        }
 public abstract void Login(IChannelHandlerContext context, ConnectPacket packet);
Ejemplo n.º 8
0
        public async Task Login(IChannelHandlerContext context, ConnectPacket packet)
        {
            string deviceId = packet.ClientId;
            var    message  = TransportMessage.CreateInvokeMessage(new RemoteInvokeMessage()
            {
                ServiceId = $"Connect", Parameters = new Dictionary <string, object> {
                    { "packet", packet }
                }
            });

            WirteDiagnosticBefore(message, context.Channel.RemoteAddress.ToString(), deviceId, packet.PacketType);
            if (string.IsNullOrEmpty(deviceId))
            {
                await ConnAck(context, new ConnAckPacket
                {
                    ReturnCode = ConnectReturnCode.RefusedIdentifierRejected
                });

                return;
            }

            var mqttBehavior = _mqttBehaviorProvider.GetMqttBehavior();

            if (mqttBehavior != null)
            {
                if (packet.HasPassword && packet.HasUsername &&
                    await mqttBehavior.Authorized(packet.Username, packet.Password))
                {
                    var mqttChannel = _channelService.GetMqttChannel(deviceId);
                    if (mqttChannel == null || !await mqttChannel.IsOnine())
                    {
                        byte[] bytes = null;
                        if (packet.WillMessage != null)
                        {
                            bytes = new byte[packet.WillMessage.ReadableBytes];
                            packet.WillMessage.ReadBytes(bytes);
                        }
                        await _channelService.Login(context.Channel, deviceId, new ConnectMessage
                        {
                            CleanSession       = packet.CleanSession,
                            ClientId           = packet.ClientId,
                            Duplicate          = packet.Duplicate,
                            HasPassword        = packet.HasPassword,
                            HasUsername        = packet.HasUsername,
                            HasWill            = packet.HasWill,
                            KeepAliveInSeconds = packet.KeepAliveInSeconds,
                            Password           = packet.Password,
                            ProtocolLevel      = packet.ProtocolLevel,
                            ProtocolName       = packet.ProtocolName,
                            Qos                  = (int)packet.QualityOfService,
                            RetainRequested      = packet.RetainRequested,
                            Username             = packet.Username,
                            WillMessage          = bytes,
                            WillQualityOfService = (int)packet.WillQualityOfService,
                            WillRetain           = packet.WillRetain,
                            WillTopic            = packet.WillTopicName
                        });
                    }
                }
                else
                {
                    await  ConnAck(context, new ConnAckPacket
                    {
                        ReturnCode = ConnectReturnCode.RefusedBadUsernameOrPassword
                    });
                }
            }
            else
            {
                await ConnAck(context, new ConnAckPacket
                {
                    ReturnCode = ConnectReturnCode.RefusedServerUnavailable
                });
            }
            WirteDiagnosticAfter(message);
        }
Ejemplo n.º 9
0
        public static Packet DecodePacket(DataReader reader)
        {
            reader.ByteOrder = ByteOrder.BigEndian;
            int signature       = reader.ReadByte();
            int remainingLength = DecodeRemainingLength(reader);

            if (Signatures.IsPublish(signature))
            {
                var qualityOfService =
                    (QualityOfService)((signature >> 1) &
                                       0x3); // take bits #1 and #2 ONLY and convert them into QoS value
                if (qualityOfService == QualityOfService.Reserved)
                {
                    throw new Exception(
                              $"Unexpected QoS value of {(int)qualityOfService} for {PacketType.PUBLISH} packet.");
                }

                bool duplicate = (signature & 0x8) == 0x8; // test bit#3
                bool retain    = (signature & 0x1) != 0;   // test bit#0
                var  packet    = new PublishPacket(qualityOfService, duplicate, retain);
                DecodePublishPacket(reader, packet, ref remainingLength);
                return(packet);
            }

            switch (signature & 240)  // We don't care about flags for these packets
            {
            // case Signatures.Subscribe & 240:
            //     var subscribePacket = new SubscribePacket();
            //     DecodePacketIdVariableHeader(reader, subscribePacket, ref remainingLength);
            //     DecodeSubscribePayload(buffer, subscribePacket, ref remainingLength);
            //     return subscribePacket;
            case Signatures.Connect:
                var connectPacket = new ConnectPacket();
                DecodeConnectPacket(reader, connectPacket, ref remainingLength);
                return(connectPacket);

            case Signatures.PubAck:
                var pubAckPacket = new PubAckPacket();
                DecodePacketIdVariableHeader(reader, pubAckPacket, ref remainingLength);
                return(pubAckPacket);

            case Signatures.ConnAck:
                var connAckPacket = new FbnsConnAckPacket();
                DecodeConnAckPacket(reader, connAckPacket, ref remainingLength);
                return(connAckPacket);

            case Signatures.SubAck:
                var subAckPacket = new SubAckPacket();
                DecodePacketIdVariableHeader(reader, subAckPacket, ref remainingLength);
                DecodeSubAckPayload(reader, subAckPacket, ref remainingLength);
                return(subAckPacket);

            case Signatures.UnsubAck:
                var unsubAckPacket = new UnsubAckPacket();
                DecodePacketIdVariableHeader(reader, unsubAckPacket, ref remainingLength);
                return(unsubAckPacket);

            case Signatures.PingResp:
                return(PingRespPacket.Instance);

            default:
                throw new Exception($"Packet type {signature} not supported");
            }
        }
Ejemplo n.º 10
0
        static void DecodeConnectPacket(DataReader buffer, ConnectPacket packet, ref int remainingLength)
        {
            string protocolName = DecodeString(buffer, ref remainingLength);

            // if (!PROTOCOL_NAME.Equals(protocolName, StringComparison.Ordinal))
            // {
            //     throw new Exception($"Unexpected protocol name. Expected: {PROTOCOL_NAME}. Actual: {protocolName}");
            // }
            packet.ProtocolName = protocolName;

            DecreaseRemainingLength(ref remainingLength, 1);
            packet.ProtocolLevel = buffer.ReadByte();

            // if (packet.ProtocolLevel != Util.ProtocolLevel)
            // {
            //     var connAckPacket = new ConnAckPacket();
            //     connAckPacket.ReturnCode = ConnectReturnCode.RefusedUnacceptableProtocolVersion;
            //     context.WriteAndFlushAsync(connAckPacket);
            //     throw new Exception($"Unexpected protocol level. Expected: {Util.ProtocolLevel}. Actual: {packet.ProtocolLevel}");
            // }

            DecreaseRemainingLength(ref remainingLength, 1);
            int connectFlags = buffer.ReadByte();

            packet.CleanSession = (connectFlags & 0x02) == 0x02;

            bool hasWill = (connectFlags & 0x04) == 0x04;

            if (hasWill)
            {
                packet.HasWill              = true;
                packet.WillRetain           = (connectFlags & 0x20) == 0x20;
                packet.WillQualityOfService = (QualityOfService)((connectFlags & 0x18) >> 3);
                if (packet.WillQualityOfService == QualityOfService.Reserved)
                {
                    throw new Exception($"[MQTT-3.1.2-14] Unexpected Will QoS value of {(int)packet.WillQualityOfService}.");
                }
                packet.WillTopicName = string.Empty;
            }
            else if ((connectFlags & 0x38) != 0) // bits 3,4,5 [MQTT-3.1.2-11]
            {
                throw new Exception("[MQTT-3.1.2-11]");
            }

            packet.HasUsername = (connectFlags & 0x80) == 0x80;
            packet.HasPassword = (connectFlags & 0x40) == 0x40;
            if (packet.HasPassword && !packet.HasUsername)
            {
                throw new Exception("[MQTT-3.1.2-22]");
            }
            if ((connectFlags & 0x1) != 0) // [MQTT-3.1.2-3]
            {
                throw new Exception("[MQTT-3.1.2-3]");
            }

            packet.KeepAliveInSeconds = DecodeUnsignedShort(buffer, ref remainingLength);

            string clientId = DecodeString(buffer, ref remainingLength);

            if (string.IsNullOrEmpty(clientId))
            {
                throw new Exception("Client identifier is required.");
            }
            packet.ClientId = clientId;

            if (hasWill)
            {
                packet.WillTopicName = DecodeString(buffer, ref remainingLength);
                var willMessageLength = DecodeUnsignedShort(buffer, ref remainingLength);
                DecreaseRemainingLength(ref remainingLength, willMessageLength);
                packet.WillMessage = buffer.ReadBuffer(willMessageLength);
            }

            if (packet.HasUsername)
            {
                packet.Username = DecodeString(buffer, ref remainingLength);
            }

            if (packet.HasPassword)
            {
                packet.Password = DecodeString(buffer, ref remainingLength);
            }
        }