Example #1
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var packet        = (DatagramPacket)message;
            var packetContent = packet.Content;

            var ctxAttribute = context.GetAttribute(Session.SessionIdentity);

            var session = ctxAttribute.Get();

            if (session == null)
            {
                var sessionId  = SessionManager.Instance.GetNewSessionId();
                var newsession = Session.Create(context.Channel, packet.Sender, sessionId);

                //用户连入数已达到最大
                if (sessionId == NetworkOperationCode.MAX_CONN_EXCEED)
                {
                }
                else
                {
                    ctxAttribute.Set(newsession);
                    //mConnectAcceptAction(session);
                }
            }
        }
        private void BeginHandshake(IChannelHandlerContext ctx)
        {
            if (_isServer)
            {
#if NETCOREAPP_2_0_GREATER || NETSTANDARD_2_0_GREATER
                // Adapt to the SslStream signature
                ServerCertificateSelectionCallback selector = null;
                if (_serverCertificateSelector is object)
                {
                    X509Certificate LocalServerCertificateSelection(object sender, string name)
                    {
                        ctx.GetAttribute(SslStreamAttrKey).Set(_sslStream);
                        return(_serverCertificateSelector(ctx, name));
                    }

                    selector = new ServerCertificateSelectionCallback(LocalServerCertificateSelection);
                }

                var sslOptions = new SslServerAuthenticationOptions()
                {
                    ServerCertificate = _serverCertificate,
                    ServerCertificateSelectionCallback = selector,
                    ClientCertificateRequired          = _serverSettings.NegotiateClientCertificate,
                    EnabledSslProtocols            = _serverSettings.EnabledProtocols,
                    CertificateRevocationCheckMode = _serverSettings.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
                    ApplicationProtocols           = _serverSettings.ApplicationProtocols // ?? new List<SslApplicationProtocol>()
                };
                _serverSettings.OnAuthenticate?.Invoke(ctx, _serverSettings, sslOptions);

                var cts = new CancellationTokenSource(_serverSettings.HandshakeTimeout);
                _sslStream.AuthenticateAsServerAsync(sslOptions, cts.Token)
                .ContinueWith(
Example #3
0
        public override void ChannelActive(IChannelHandlerContext context)
        {
            var sessionAttribute = context.GetAttribute(Session.SessionIdentity);
            var session          = sessionAttribute.Get();
            var buffer           = context.Allocator.Buffer().WithOrder(ByteOrder.LittleEndian);

            //新客户连入
            if (session == null)
            {
                var sessionId  = SessionManager.Instance.GetNewSessionId();
                var newsession = Session.Create(context.Channel, context.Channel.RemoteAddress, sessionId);

                //var randomKeyBytes = new byte[sizeof(int)];
                //Randomizer.GetBytes(randomKeyBytes);
                //var randomKey = BitConverter.ToInt32(randomKeyBytes, 0);

                ////用户连入数已达到最大
                //if (sessionId == NetworkOperationCode.MAX_CONN_EXCEED)
                //{
                //    SimplePacketCreator.HandshakeRefuse(buffer);
                //}
                //else
                //{
                sessionAttribute.Set(newsession);
                SessionManager.Instance.AddSession(context.Channel.RemoteAddress, newsession);

                //    SimplePacketCreator.HandshakeAccept(buffer, sessionId, randomKey, 0, 1);
                //}

                //context.WriteAndFlushAsync(buffer);
            }
        }
Example #4
0
        protected override void Encode(IChannelHandlerContext context, MaplePakcet message, IByteBuffer output)
        {
            using (message)
            {
                CMapleClient client = context.GetAttribute <CMapleClient>(CMapleClient.attributeKey).Get();
                if (client == null)
                {
                    output.WriteBytes(message.ToArray());
                }
                else
                {
                    //加密
                    using (MapleBuffer buffer = new MapleBuffer())
                    {
                        byte[] header = new byte[4];
                        client.m_SendIv.GetHeaderToClient(message.ToArray().Length, header);
                        client.m_SendIv.Transform();
                        buffer.add(header);
                        buffer.add(message.ToArray());

                        System.Console.WriteLine("发送封包:{0}", HexTool.toString(message.ToArray()));
                        output.WriteBytes(buffer.ToArray());
                    }
                }
            }
        }
Example #5
0
 /// <summary>
 /// 设置登录状态
 /// </summary>
 /// <param name="context"></param>
 /// <param name="isLoginSuccess"></param>
 public static void SetLoginState(IChannelHandlerContext context, bool isLoginSuccess)
 {
     context.GetAttribute <LoginState>(LoginStateKey).Set(new LoginState()
     {
         IsLoginSuccess = isLoginSuccess
     });
 }
Example #6
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            CMapleClient client = context.GetAttribute <CMapleClient>(CMapleClient.attributeKey).Get();

            if (client.DecoderState == -1)
            {
                //检测长度
                if (input.WriterIndex >= 4)
                {
                    int packetHeader = input.ReadInt();
                    client.DecoderState = MapleCipher.getPacketLength(packetHeader);//MapleAESOFB.getPacketLength(packetHeader);
                    int aaa = 0;
                    client.m_RecvIv.Transform();
                }
                else
                {
                    return;
                }
            }


            if (input.ReadableBytes >= client.DecoderState)
            {
                client.DecoderState = -1;
                //IntPtr DecoderState = context.GetAttribute<IntPtr>(MapleClient.DecoderState).Get();
                //获取数据长度,创建一个空数组
                byte[] DecodePakcet = new byte[input.ReadableBytes];

                //读取正常数据区域
                input.ReadBytes(DecodePakcet);
                //解密成功后返回数据
                output.Add(DecodePakcet);
            }
        }
Example #7
0
 protected override void Decode(IChannelHandlerContext context, IByteBuffer message, List <object> output)
 {
     output.Add(new MessageContext
     {
         Session = context.GetAttribute(ChannelAttributes.Session).Get(),
         Message = message.Retain()
     });
 }
Example #8
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            AttributeKey <NiftyConnectionContext> key = AttributeKey <NiftyConnectionContext> .ValueOf(NiftyConnectionContextKey);

            NiftyConnectionContext nContext = context.GetAttribute <NiftyConnectionContext>(key).Get();

            base.ChannelRead(context, message);
        }
Example #9
0
        public override void ChannelInactive(IChannelHandlerContext context)
        {
            var player = context.GetAttribute(Constants.PlayerAttributeKey).GetAndRemove();

            _world.Remove(player);
            _logger.Information("Player: {0} disconnected Addr: {1}", player.Username, context.Channel.RemoteAddress);
            base.ChannelInactive(context);
        }
Example #10
0
        public override void ChannelActive(IChannelHandlerContext context)
        {
            base.ChannelActive(context);
            NiftyConnectionContext ncontext = new NiftyConnectionContext();

            ncontext.RemoteAddress = context.Channel.RemoteAddress;
            AttributeKey <NiftyConnectionContext> key = AttributeKey <NiftyConnectionContext> .ValueOf(NiftyConnectionContextKey);

            context.GetAttribute <NiftyConnectionContext>(key).Set(ncontext);
        }
Example #11
0
        public static Guid GetUserId(this IChannelHandlerContext channel)
        {
            var value = channel.GetAttribute(ATTR_KEY_USER_ID).Get();

            if (string.IsNullOrWhiteSpace(value))
            {
                return(Guid.Empty);
            }

            return(Guid.Parse(value));
        }
Example #12
0
        public static DateTime?GetReaderTime(this IChannelHandlerContext channel)
        {
            var value = channel.GetAttribute(ATTR_KEY_READER_TIME).Get();

            if (string.IsNullOrWhiteSpace(value))
            {
                return(null);
            }

            return(Convert.ToDateTime(value));
        }
Example #13
0
        public override void ChannelActive(IChannelHandlerContext contex)
        {
            IAttribute <string> der = contex.GetAttribute(AttributeMapConstant.HttpAttriKey);

            if (string.IsNullOrWhiteSpace(der.Get()))
            {
                der.SetIfAbsent($"会重置:{GetType().Name}");
            }
            IAttribute <string> parentAtt = contex.Channel.Parent.GetAttribute(AttributeMapConstant.HttpAttriKey);

            if (string.IsNullOrWhiteSpace(parentAtt.Get()))
            {
                parentAtt.SetIfAbsent($"不会重置:{GetType().Name}");
            }
        }
Example #14
0
            private static DispatcherContext GetDispatcherContext(IChannelHandlerContext ctx)
            {
                AttributeKey <DispatcherContext> key = AttributeKey <DispatcherContext> .ValueOf(DispatcherContext.AttributeKey);

                var attachment = ctx.GetAttribute(key);
                DispatcherContext dispatcherContext = attachment.Get();

                if (dispatcherContext == null)
                {
                    // No context was added yet, add one
                    dispatcherContext = new DispatcherContext();
                    attachment.Set(dispatcherContext);
                }

                return(dispatcherContext);
            }
Example #15
0
        public override void ChannelActive(IChannelHandlerContext context)
        {
            System.Console.WriteLine("发现用户:" + context.Channel.RemoteAddress.ToString());
            //027配套

            //创建一个客户端
            byte[]       ivRecv = { 70, 114, 122, 82 };
            byte[]       ivSend = { 82, 48, 120, 115 };
            CMapleClient client = new CMapleClient(27, ivRecv, ivSend, context.Channel);

            context.Channel.WriteAndFlushAsync(GetHello(27, ivRecv, ivSend));


            //设置客户端
            context.GetAttribute <CMapleClient>(CMapleClient.attributeKey).Set(client);
        }
Example #16
0
        private void HandleLoginProcessorResponse(Player player, LoginStatus response, IChannelHandlerContext ctx, IsaacRandomPair randomPair)
        {
            if (response != LoginStatus.StatusOk)
            {
                ctx.CloseAsync();
            }
            else
            {
                if (player == null)
                {
                    ctx.CloseAsync();
                    throw new InvalidOperationException("Cannot initialize player is null");
                }

                ctx.Channel.Pipeline.Remove(nameof(LoginEncoder));
                ctx.Channel.Pipeline.Remove(nameof(LoginDecoder));
                var gameMessageHandlers = _gameMessageProvider.Provide();

                foreach (var gameMessageHandler in gameMessageHandlers)
                {
                    if (gameMessageHandler is ICipherAwareHandler)
                    {
                        ((ICipherAwareHandler)gameMessageHandler).CipherPair = randomPair;
                    }

                    if (gameMessageHandler is IPlayerAwareHandler)
                    {
                        ((IPlayerAwareHandler)gameMessageHandler).Player = player;
                    }
                }
                ctx.Channel.Pipeline.AddLast(gameMessageHandlers);
                ctx.GetAttribute(Constants.PlayerAttributeKey).SetIfAbsent(player);
                player.ChannelHandlerContext = ctx;
                _world.Add(player);
                if (!_reconnecting)
                {
                    _ = _playerInitializer.InitializeAsync(player);
                }
                else
                {
                    player.UpdateAppearance();
                }
            }
        }
        protected override async void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            try
            {
                tenancyContext = context.GetAttribute <AbstractTenancyContext>(AttributeKey <AbstractTenancyContext> .ValueOf(AbstractTenancyContext.TENANCY_CONTEXT_KEY)).Get();
                var dataPacket = await tenancyContext?.Decode(input);

                dataPacket.EventTopicAddress = GetDeviceD2CAddress(dataPacket.DeviceId);
                var connectPacket = await GetDeviceCredentialAsync(tenancyContext.TenantId, dataPacket.DeviceId);

                output.Add(new Dictionary <PacketType, Packet>()
                {
                    { PacketType.CONNECT, connectPacket }, { PacketType.D2C, dataPacket }
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
Example #18
0
        //private static volatile IChannelGroup group;
        public override void ChannelActive(IChannelHandlerContext contex)
        {
            IAttribute <string>        der       = contex.GetAttribute(AttributeMapConstant.HttpAttriKey);
            IAttribute <IChannelGroup> parentAtt = contex.Channel.Parent.GetAttribute(AttributeMapConstant.SockerGroup);
            IChannelGroup g = parentAtt.Get();

            if (g == null)
            {
                lock (this)
                {
                    if (g == null)
                    {
                        var chennGroup = new DefaultChannelGroup(contex.Executor);
                        g = chennGroup;
                        parentAtt.SetIfAbsent(chennGroup);
                    }
                }
            }
            contex.WriteAndFlushAsync(string.Format("Welcome to {0} secure chat server!{1}", Dns.GetHostName(), delimiterStr));
            g.Add(contex.Channel);
        }
Example #19
0
        protected override void Decode(IChannelHandlerContext ctx, IFullHttpRequest req, List <object> output)
        {
            // Handle a bad request.
            if (!req.Result.IsSuccess)
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, BadRequest));
                return;
            }

            // Allow only GET methods.
            if (!Equals(req.Method, HttpMethod.Get))
            {
                SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, Forbidden));
                return;
            }

            // Handshake
            var wsFactory = new WebSocketServerHandshakerFactory(
                GetWebSocketLocation(req), null, true, 5 * 1024 * 1024);
            var handshaker = wsFactory.NewHandshaker(req);

            if (handshaker == null)
            {
                WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel);
            }
            else
            {
                handshaker.HandshakeAsync(ctx.Channel, req);
            }

            ctx.GetAttribute(wshsKey).Set(handshaker);
            var connectionInfo = channelGroup.FindConnectionInfo(ctx.Channel);

            if (connectionInfo == null)
            {
                channelGroup.Add(new ConnectionInfo(ctx.Channel, this.Options));
            }
            ctx.Channel.Pipeline.FireUserEventTriggered(new HandShakeEvent());
        }
        protected override void ChannelRead0(IChannelHandlerContext ctx, WebSocketFrame frame)
        {
            WebSocketServerHandshaker handshaker = ctx.GetAttribute(wshsKey).Get();

            // Check for closing frame
            if (frame is CloseWebSocketFrame)
            {
                handshaker.CloseAsync(ctx.Channel, (CloseWebSocketFrame)frame.Retain());
                return;
            }

            if (frame is PingWebSocketFrame)
            {
                ctx.WriteAsync(new PongWebSocketFrame((IByteBuffer)frame.Content.Retain()));
                return;
            }

            if (frame is TextWebSocketFrame text)
            {
                var uri     = text.Text();
                var textmsg = messageFactory.Parse(uri);
                if (textmsg != null)
                {
                    ctx.FireChannelRead(textmsg);
                }
                return;
            }

            if (frame is BinaryWebSocketFrame)
            {
                var binarymsg = messageFactory.Parse(frame.Content);
                if (binarymsg != null)
                {
                    ctx.FireChannelRead(binarymsg);
                }
                return;
            }
        }
Example #21
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var tenancyContext = context.GetAttribute <AbstractTenancyContext>(AttributeKey <AbstractTenancyContext> .ValueOf(AbstractTenancyContext.TENANCY_CONTEXT_KEY)).Get();

            this.messagingBridgeFactory = tenancyContext.IotBridgeFactory;


            var packets = message as IDictionary <PacketType, Packet>;

            if (packets == null || (packets != null && packets.Count <= 0))
            {
                Console.WriteLine(($"No messages (`{typeof(Packet).FullName}` ) received"));
                return;
            }

            var connectPacket = packets[PacketType.CONNECT] as ConnectPacket;
            var dataPacket    = packets[PacketType.D2C] as DeviceDataPacket;

            this.lastClientActivityTime = DateTime.Now;
            if (this.IsInState(StateFlags.Connected))   //Already Connected, process DeviceDataPacket
            {
                this.ProcessPacket(context, dataPacket);
            }
            else if (this.IsInState(StateFlags.ProcessingConnect))   //Connect processing in progress, queue newer connect requests
            {
                //TODO Implement queue/ priority queue based on supported cases
                Queue <Packet> queue = this.connectPendingQueue ?? (this.connectPendingQueue = new Queue <Packet>(4));
                queue.Enqueue(dataPacket);
            }
            else
            {
                //Not Connected and Not processing a connect - Use connect packet to create connection to IoTHub
                this.dataPacketWithConnect = dataPacket;
                this.ProcessPacket(context, connectPacket);
            }

            context.WriteAsync(message);
        }
Example #22
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            try
            {
                MapleBuffer buffer = new MapleBuffer((byte[])message);
                if (buffer.Available < 2)
                {
                    return;
                }
                System.Console.WriteLine("封包: {0}", buffer.ToString());

                CMapleClient client = context.GetAttribute <CMapleClient>(CMapleClient.attributeKey).Get();
                if (client != null)
                {
                    short packetId = buffer.read <byte>();
                    CommonGlobal.Run(packetId, buffer, client);
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine("错误:" + e);
            }
        }
 public IAttribute <T> GetAttribute <T>(AttributeKey <T> key) where T : class => _ctx.GetAttribute(key);
Example #24
0
 /// <summary>
 /// 获取登录状态
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public static LoginState GetLoginState(IChannelHandlerContext context)
 {
     return(context.GetAttribute <LoginState>(LoginStateKey).Get());
 }
Example #25
0
 /// <summary>
 /// 移除登录状态
 /// </summary>
 /// <param name="context"></param>
 public static void RemoveLoginState(IChannelHandlerContext context)
 {
     context.GetAttribute <LoginState>(LoginStateKey).Remove();
 }
Example #26
0
 public static void UpdateReaderTime(this IChannelHandlerContext channel, DateTime time)
 {
     channel.GetAttribute(ATTR_KEY_READER_TIME).Set(time.ToString());
 }
Example #27
0
        private bool EnsureAuthenticated(IChannelHandlerContext ctx)
        {
            var oldState = State;

            if (!oldState.HasAny(TlsHandlerState.AuthenticationStarted))
            {
                State = oldState | TlsHandlerState.Authenticating;
                if (_isServer)
                {
#if NETCOREAPP_2_0_GREATER || NETSTANDARD_2_0_GREATER
                    // Adapt to the SslStream signature
                    ServerCertificateSelectionCallback selector = null;
                    if (_serverCertificateSelector is object)
                    {
                        X509Certificate LocalServerCertificateSelection(object sender, string name)
                        {
                            ctx.GetAttribute(SslStreamAttrKey).Set(_sslStream);
                            var cert = _serverCertificateSelector(ctx, name);

                            if (cert is object)
                            {
                                EnsureCertificateIsAllowedForServerAuth(cert);
                            }
                            return(cert);
                        }

                        selector = new ServerCertificateSelectionCallback(LocalServerCertificateSelection);
                    }

                    var sslOptions = new SslServerAuthenticationOptions()
                    {
                        ServerCertificate = _serverCertificate,
                        ServerCertificateSelectionCallback = selector,
                        ClientCertificateRequired          = _serverSettings.NegotiateClientCertificate,
                        EnabledSslProtocols            = _serverSettings.EnabledProtocols,
                        CertificateRevocationCheckMode = _serverSettings.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
                        ApplicationProtocols           = _serverSettings.ApplicationProtocols // ?? new List<SslApplicationProtocol>()
                    };
                    if (_hasHttp2Protocol)
                    {
                        // https://tools.ietf.org/html/rfc7540#section-9.2.1
                        sslOptions.AllowRenegotiation = false;
                    }
                    _sslStream.AuthenticateAsServerAsync(sslOptions, CancellationToken.None)
                    .ContinueWith(s_handshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
#else
                    var serverCert = _serverCertificate;
                    if (_serverCertificateSelector is object)
                    {
                        ctx.GetAttribute(SslStreamAttrKey).Set(_sslStream);
                        var serverCert2 = _serverCertificateSelector(ctx, null);
                        if (serverCert2 is object)
                        {
                            EnsureCertificateIsAllowedForServerAuth(serverCert2);
                            serverCert = serverCert2;
                        }
                    }
                    _sslStream.AuthenticateAsServerAsync(serverCert,
                                                         _serverSettings.NegotiateClientCertificate,
                                                         _serverSettings.EnabledProtocols,
                                                         _serverSettings.CheckCertificateRevocation)
                    .ContinueWith(s_handshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
#endif
                }
                else
                {
#if NETCOREAPP_2_0_GREATER || NETSTANDARD_2_0_GREATER
                    LocalCertificateSelectionCallback selector = null;
                    if (_userCertSelector is object)
                    {
                        X509Certificate LocalCertificateSelection(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
                        {
                            ctx.GetAttribute(SslStreamAttrKey).Set(_sslStream);
                            return(_userCertSelector(ctx, targetHost, localCertificates, remoteCertificate, acceptableIssuers));
                        }

                        selector = new LocalCertificateSelectionCallback(LocalCertificateSelection);
                    }
                    var sslOptions = new SslClientAuthenticationOptions()
                    {
                        TargetHost                        = _clientSettings.TargetHost,
                        ClientCertificates                = _clientSettings.X509CertificateCollection,
                        EnabledSslProtocols               = _clientSettings.EnabledProtocols,
                        CertificateRevocationCheckMode    = _clientSettings.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
                        LocalCertificateSelectionCallback = selector,
                        ApplicationProtocols              = _clientSettings.ApplicationProtocols
                    };
                    if (_hasHttp2Protocol)
                    {
                        // https://tools.ietf.org/html/rfc7540#section-9.2.1
                        sslOptions.AllowRenegotiation = false;
                    }
                    _sslStream.AuthenticateAsClientAsync(sslOptions, CancellationToken.None)
                    .ContinueWith(s_handshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
#else
                    _sslStream.AuthenticateAsClientAsync(_clientSettings.TargetHost,
                                                         _clientSettings.X509CertificateCollection,
                                                         _clientSettings.EnabledProtocols,
                                                         _clientSettings.CheckCertificateRevocation)
                    .ContinueWith(s_handshakeCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously);
#endif
                }
                return(false);
            }

            return(oldState.Has(TlsHandlerState.Authenticated));
        }
Example #28
0
 public static void SetUserId(this IChannelHandlerContext channel, Guid userId)
 {
     channel.GetAttribute(ATTR_KEY_USER_ID).Set(userId.ToString());
 }