Example #1
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet)
        {
            var content = packet.Content;
            var address = packet.Sender;

            byte[] msg = new byte[content.ReadableBytes];
            content.ReadBytes(msg);

            if (msg.Length < 98)
            {
                _logger.Error($"Incorrect message, length: {msg.Length}, sender: {address}");
                ctx.DisconnectAsync();
                return;
            }

            var typeRaw = msg[97];

            if (!Enum.IsDefined(typeof(MessageType), (int)typeRaw))
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Unsupported message type: {typeRaw}, sender: {address}, message {msg.ToHexString()}");
                }
                ctx.DisconnectAsync();
                return;
            }

            var type = (MessageType)typeRaw;

            if (_logger.IsTrace)
            {
                _logger.Trace($"Received message: {type}");
            }

            DiscoveryMessage message;

            try
            {
                message            = Deserialize(type, msg);
                message.FarAddress = (IPEndPoint)address;
            }
            catch (Exception e)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Error during deserialization of the message, type: {type}, sender: {address}, msg: {msg.ToHexString()}, {e.Message}");
                }
                return;
            }

            try
            {
                _discoveryManager.OnIncomingMessage(message);
            }
            catch (Exception e)
            {
                _logger.Error($"Error while processing message, type: {type}, sender: {address}, message: {message}", e);
            }
        }
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            //In case of SocketException we log it as debug to avoid noise
            string clientId = _session?.Node?.ToString("c") ?? $"unknown {_session?.RemoteHost}";

            if (exception is SocketException)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Error in communication with {clientId} (SocketException): {exception}");
                }
            }
            else
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Error in communication with {clientId}: {exception}");
                }
            }

            if (_session?.Node?.IsStatic != true)
            {
                context.DisconnectAsync().ContinueWith(x =>
                {
                    if (x.IsFaulted && _logger.IsTrace)
                    {
                        _logger.Trace($"Error while disconnecting on context on {this} : {x.Exception}");
                    }
                });
            }
            else
            {
                base.ExceptionCaught(context, exception);
            }
        }
        public virtual async Task Process(IChannelHandlerContext ctx, RpcMessage rpcMessage)
        {
            if (ChannelManager.IsRegistered(ctx.Channel))
            {
                await OnRequestMessage(ctx, rpcMessage);
            }
            else
            {
                try
                {
                    if (Logger().IsEnabled(LogLevel.Debug))
                    {
                        Logger().LogInformation($"closeChannelHandlerContext channel:{ctx.Channel}");
                    }
                    await ctx.DisconnectAsync();

                    await ctx.CloseAsync();
                }
                catch (Exception exx)
                {
                    Logger().LogError(exx, exx.Message);
                }
                if (Logger().IsEnabled(LogLevel.Debug))
                {
                    Logger().LogInformation($"close a unhandled connection! [{ctx.Channel}]");
                }
            }
        }
Example #4
0
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            //In case of SocketException we log it as debug to avoid noise
            if (exception is SocketException)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Exception when processing discovery messages (SocketException): {exception}");
                }
            }
            else
            {
                if (_logger.IsError)
                {
                    _logger.Error("Exception when processing discovery messages", exception);
                }
            }

            context.DisconnectAsync().ContinueWith(x =>
            {
                if (x.IsFaulted && _logger.IsTrace)
                {
                    _logger.Trace($"Error while disconnecting on context on {this} : {x.Exception}");
                }
            });
        }
Example #5
0
        public virtual async Task Process(IChannelHandlerContext ctx, RpcMessage rpcMessage)
        {
            if (_futures.TryRemove(rpcMessage.Id, out MessageFuture messageFuture) && messageFuture != null)
            {
                messageFuture.ResultMessage = rpcMessage.Body;
            }
            else
            {
                if (ChannelManager.IsRegistered(ctx.Channel))
                {
                    await OnResponseMessage(ctx, rpcMessage);
                }
                else
                {
                    try
                    {
                        if (Logger().IsEnabled(LogLevel.Debug))
                        {
                            Logger().LogInformation("closeChannelHandlerContext channel:" + ctx.Channel);
                        }
                        await ctx.DisconnectAsync();

                        await ctx.CloseAsync();
                    }
                    catch (Exception exx)
                    {
                        Logger().LogError(exx, exx.Message);
                    }
                    if (Logger().IsEnabled(LogLevel.Debug))
                    {
                        Logger().LogInformation($"close a unhandled connection! [{ctx.Channel}]");
                    }
                }
            }
        }
 public void Disconnect()
 {
     if (channelHandlerContext != null)
     {
         channelHandlerContext.DisconnectAsync();
     }
 }
 public override Task DisconnectAsync(IChannelHandlerContext ctx)
 {
     if (this.Logger.IsEnabled(this.InternalLevel))
     {
         this.Logger.Log(this.InternalLevel, this.Format(ctx, "DISCONNECT"));
     }
     return(ctx.DisconnectAsync());
 }
Example #8
0
 /// <inheritdoc />
 public override void Disconnect(IChannelHandlerContext ctx, IPromise promise)
 {
     if (Logger.IsEnabled(MsLogLevel.Information))
     {
         Logger.LogInformation("Channel {0} disconnect", ctx.Channel);
     }
     ctx.DisconnectAsync(promise);
 }
Example #9
0
 public override void Disconnect(IChannelHandlerContext ctx, IPromise promise)
 {
     if (Logger.IsEnabled(InternalLevel))
     {
         Logger.Log(InternalLevel, Format(ctx, "DISCONNECT"));
     }
     ctx.DisconnectAsync(promise);
 }
Example #10
0
 public void Error_on_context_when_disconnecting_channels_does_not_prevent_the_event()
 {
     bool wasCalled = false;
     Session session = new(30312, new Node(TestItem.PublicKeyA, "127.0.0.1", 8545), _channel, NullDisconnectsAnalyzer.Instance, LimboLogs.Instance);
     _channelHandlerContext.DisconnectAsync().Returns(Task.FromException<Exception>(new Exception()));
     session.Disconnected += (s, e) => wasCalled = true;
     session.Handshake(TestItem.PublicKeyA);
     session.Init(5, _channelHandlerContext, _packetSender);
     session.MarkDisconnected(DisconnectReason.Other, DisconnectType.Local, "test");
     Assert.True(wasCalled);
 }
Example #11
0
        public void Dispose()
        {
            if (GetHabbo() != null)
            {
                GetHabbo().OnDisconnect();
            }

            MachineId     = string.Empty;
            _disconnected = true;
            _habbo        = null;
            channel.DisconnectAsync();
        }
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            //In case of SocketException we log it as debug to avoid noise
            if (exception is SocketException)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Exception when processing discovery messages (SocketException): {exception}");
                }
            }
            else
            {
                if (_logger.IsError)
                {
                    _logger.Error("Exception when processing discovery messages", exception);
                }
            }

            context.DisconnectAsync();
        }
Example #13
0
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            //In case of SocketException we log it as debug to avoid noise
            string clientId = _session?.Node?.ToString("c") ?? $"unknown {_session?.RemoteHost}";

            if (exception is SocketException)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Error in communication with {clientId} (SocketException): {exception}");
                }
            }
            else
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Error in communication with {clientId}: {exception}");
                }
            }

            context.DisconnectAsync();
        }
 public Task DisconnectAsync(IChannelHandlerContext context)
 {
     return context.DisconnectAsync();
 }
        private void HandleRpcError(IChannelHandlerContext ctx, long messageReqMsgId, TRpcError error)
        {
            Log.Warn($"#{ClientSettings.ClientSession.SessionId}: Recieve error from server: {error.ErrorMessage}");
            if (Log.IsDebugEnabled)
            {
                var jMessages = JsonConvert.SerializeObject(error);
                Log.Debug(jMessages);
            }

            switch (error.ErrorMessage)
            {
            case "PHONE_CODE_INVALID":
                RequestService.ReturnException(messageReqMsgId, new PhoneCodeInvalidException());
                break;

            case "SESSION_PASSWORD_NEEDED":
                RequestService.ReturnException(messageReqMsgId, new CloudPasswordNeededException());
                break;

            case var phoneMigrate when phoneMigrate.StartsWith("PHONE_MIGRATE_"):
            case var userMigrate when userMigrate.StartsWith("USER_MIGRATE_"):
            case var netwokMigrate when netwokMigrate.StartsWith("NETWORK_MIGRATE_"):
                var dcNumber = int.Parse(Regex.Match(error.ErrorMessage, @"\d+").Value);

                var dcOption = ClientSettings.Config.DcOptions.First(option => option.Id == dcNumber);

                ClientSettings.ClientSession.AuthKey       = null;
                ClientSettings.ClientSession.ServerAddress = dcOption.IpAddress;
                ClientSettings.ClientSession.Port          = dcOption.Port;

                ctx.Flush();

                SessionWriter.Save(ClientSettings.ClientSession)
                .ContinueWith(_ => ctx.DisconnectAsync());
                break;

            case var fileMigrate when fileMigrate.StartsWith("FILE_MIGRATE_"):
                var fileMigrateDcNumber = Regex.Match(fileMigrate, @"\d+").Value;

                var fileMigrateDcIdx = int.Parse(fileMigrateDcNumber);

                RequestService.ReturnException(messageReqMsgId, new FileMigrationException(fileMigrateDcIdx));
                break;

            case var floodMessage when floodMessage.StartsWith("FLOOD_WAIT_"):
                var floodMessageTime = Regex.Match(floodMessage, @"\d+").Value;

                var seconds = int.Parse(floodMessageTime);

                RequestService.ReturnException(messageReqMsgId, new FloodWaitException(TimeSpan.FromSeconds(seconds)));
                break;

            case "AUTH_KEY_UNREGISTERED":
                ClientSettings.ClientSession.AuthKey = null;
                ClientSettings.ClientSession.UserId  = null;
                SessionWriter.Save(ClientSettings.ClientSession).ContinueWith(_ => RequestService.ReturnException(messageReqMsgId, new UserNotAuthorizeException()));
                break;

            default:
                RequestService.ReturnException(messageReqMsgId, new UnhandledException(error.ErrorMessage));
                break;
            }
        }
Example #16
0
 public override Task DisconnectAsync(IChannelHandlerContext ctx)
 {
     _log.Info("Channel {0} disconnect", ctx.Channel);
     return(ctx.DisconnectAsync());
 }
 public Task DisconnectAsync(IChannelHandlerContext context)
 {
     return(context.DisconnectAsync());
 }
Example #18
0
 public override Task DisconnectAsync(IChannelHandlerContext context)
 {
     _logger.Debug($"{context.Channel} DISCONNECT");
     return(context.DisconnectAsync());
 }
Example #19
0
 public override Task DisconnectAsync(IChannelHandlerContext context)
 {
     // Try to flush one last time if flushes are pending before disconnect the channel.
     ResetReadAndFlushIfNeeded(context);
     return(context.DisconnectAsync());
 }
Example #20
0
 public override Task DisconnectAsync(IChannelHandlerContext context)
 {
     RegisterFiredEvent(SupportedEvent.DisconnectAsync);
     return(context.DisconnectAsync());
 }
Example #21
0
 public override async Task DisconnectAsync(IChannelHandlerContext ctx)
 {
     Logger().LogInformation($"Channel {ctx.Channel} disconnect");
     await ctx.DisconnectAsync();
 }
Example #22
0
 public virtual void Disconnect(IChannelHandlerContext context, IPromise promise) => context.DisconnectAsync(promise);
Example #23
0
        public override Task DisconnectAsync(IChannelHandlerContext context)
        {
            Log.Debug($"{context.Name}: DisconnectAsync");

            return(context.DisconnectAsync());
        }
 public Task DisconnectAsync() => _ctx.DisconnectAsync();
 public override void Disconnect(IChannelHandlerContext ctx, IPromise promise)
 {
     // Try to flush one last time if flushes are pending before disconnect the channel.
     ResetReadAndFlushIfNeeded(ctx);
     _ = ctx.DisconnectAsync(promise);
 }
        protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet)
        {
            var content = packet.Content;
            var address = packet.Sender;

            byte[] msg = new byte[content.ReadableBytes];
            content.ReadBytes(msg);

            if (msg.Length < 98)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Incorrect discovery message, length: {msg.Length}, sender: {address}");
                }
                ctx.DisconnectAsync();
                return;
            }

            var typeRaw = msg[97];

            if (!Enum.IsDefined(typeof(MessageType), (int)typeRaw))
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Unsupported message type: {typeRaw}, sender: {address}, message {msg.ToHexString()}");
                }
                ctx.DisconnectAsync();
                return;
            }

            var type = (MessageType)typeRaw;

            if (_logger.IsTrace)
            {
                _logger.Trace($"Received message: {type}");
            }

            DiscoveryMessage message;

            try
            {
                message            = Deserialize(type, msg);
                message.FarAddress = (IPEndPoint)address;
            }
            catch (Exception e)
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug($"Error during deserialization of the message, type: {type}, sender: {address}, msg: {msg.ToHexString()}, {e.Message}");
                }
                ctx.DisconnectAsync();
                return;
            }

            try
            {
                if ((ulong)message.ExpirationTime < _timestamper.EpochSeconds)
                {
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Received a discovery message that has expired, type: {type}, sender: {address}, message: {message}");
                    }
                    ctx.DisconnectAsync();
                    return;
                }

                if (!message.FarAddress.Equals((IPEndPoint)packet.Sender))
                {
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Discovery fake IP detected - pretended {message.FarAddress} but was {ctx.Channel.RemoteAddress}, type: {type}, sender: {address}, message: {message}");
                    }
                    ctx.DisconnectAsync();
                    return;
                }

                if (message.FarPublicKey == null)
                {
                    if (_logger.IsDebug)
                    {
                        _logger.Debug($"Discovery message without a valid signature {message.FarAddress} but was {ctx.Channel.RemoteAddress}, type: {type}, sender: {address}, message: {message}");
                    }
                    ctx.DisconnectAsync();
                    return;
                }

                _discoveryManager.OnIncomingMessage(message);
            }
            catch (Exception e)
            {
                if (_logger.IsDebug)
                {
                    _logger.Error($"DEBUG/ERROR Error while processing message, type: {type}, sender: {address}, message: {message}", e);
                }
                ctx.DisconnectAsync();
            }
        }
Example #27
0
 public override Task DisconnectAsync(IChannelHandlerContext ctx)
 {
     if (this.Logger.IsEnabled(this.InternalLevel))
     {
         this.Logger.Log(this.InternalLevel, this.Format(ctx, "DISCONNECT"));
     }
     return ctx.DisconnectAsync();
 }
Example #28
0
 public virtual Task DisconnectAsync(IChannelHandlerContext context) => context.DisconnectAsync();
Example #29
0
 public override void Disconnect(IChannelHandlerContext context, IPromise promise)
 {
     Log(Event.DISCONNECT);
     context.DisconnectAsync(promise);
 }