/// <inheritdoc cref="DotNetty.Transport.Channels.SimpleChannelInboundHandler{I}"/>> protected override void ChannelRead0(IChannelHandlerContext ctx, ProtocolMessage msg) { if (_authenticationStrategy.Authenticate(msg.PeerId)) { ctx.FireChannelRead(msg); } else { ctx?.CloseAsync().ConfigureAwait(false); throw new AuthenticationException("Authentication Attempt Failed"); } }
void ContinueScenarioExecution(IChannelHandlerContext context) { if (!this.testScenario.MoveNext()) { context.CloseAsync() .ContinueWith( t => this.completion.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously); this.completion.TryComplete(); return; } foreach (object message in this.testScenario.Current.SendMessages) { context.WriteAsync(message) .ContinueWith( t => this.completion.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously); } context.Flush(); }
void ContinueScenarioExecution(IChannelHandlerContext context) { if (!this.testScenario.MoveNext()) { context.CloseAsync() .ContinueWith( t => this.completion.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously); this.completion.TryComplete(); return; } TestScenarioStep currentStep = this.testScenario.Current; if (currentStep.Delay > TimeSpan.Zero) { context.Channel.EventLoop.Schedule((ctx, state) => this.ExecuteStep((IChannelHandlerContext)ctx, (TestScenarioStep)state), context, currentStep, currentStep.Delay); } else { this.ExecuteStep(context, currentStep); } }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { if (!(exception is ObjectDisposedException)) log.Warn($"Exception in NettyServerHandler {context.Channel.Id.AsShortText()}: {exception.Message}"); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Console.WriteLine("Exception: " + exception); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { base.ExceptionCaught(context, exception); s_logger.LogError($"{exception}"); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception e) { LOGGER.Error(e, "编码消息出现错误 {}", e.Message); context.CloseAsync(); }
/// <summary> /// 异常 /// </summary> /// <param name="context"></param> /// <param name="exception"></param> public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { ClientEventHandler.RecordLogEvent?.Invoke(false, $"Exception: {exception.Message}"); ClientEventHandler.IsConnect = false; context.CloseAsync(); }
public static void NotifyHandshakeFailure(IChannelHandlerContext ctx, Exception cause) { // We have may haven written some parts of data before an exception was thrown so ensure we always flush. // See https://github.com/netty/netty/issues/3900#issuecomment-172481830 ctx.Flush(); ctx.FireUserEventTriggered(new TlsHandshakeCompletionEvent(cause)); ctx.CloseAsync(); }
public override void ChannelRead(IChannelHandlerContext context, object message) { _event.Signal(); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { // Close the connection when an exception is raised. Console.WriteLine($"{exception}"); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { _logger.ServerHandlerCaughtException(exception); context.CloseAsync(); }
public Task CloseAsync(IChannelHandlerContext context) => context.CloseAsync();
public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Console.WriteLine("Exception: " + exception); context.CloseAsync(); }
// Catches inbound message exceptions public override void ExceptionCaught(IChannelHandlerContext contex, Exception e) { Logger.Error(e); contex.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause) { Console.WriteLine(cause); ctx.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { base.ExceptionCaught(context, exception); NotifyListener(new Disassociated(DisassociateInfo.Unknown)); context.CloseAsync(); // close the channel }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Logger.Log(exception, GetType(), ErrorLevel.Error); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { //客户端主动断开需要应答,否则socket变成CLOSE_WAIT状态导致socket资源耗尽 context.CloseAsync(); _logger.LogWarning(exception, $"与服务器:{context.Channel.RemoteAddress}通信时发送了错误。"); }
protected override void ChannelRead0(IChannelHandlerContext ctx, Packet msg) { if (_authorized) { ctx.FireChannelRead(new UserPacket(msg, _auth)); } else if (!_checkAuth) { switch ((string)msg.CommandKey) { case "authByDeveloper": _authTask?.Dispose(); _authTask = Task.Factory.StartNew(() => { var authTask = _authManager.GetAuthByDevelopers(msg.ContentAs <AuthByDeveloperPacket>().DeveloperId); authTask.Wait(); _auth = authTask.Result; var info = new UserAuthInfoRequest { userAuthInfo = _auth }; InitializeUserHandler(ctx, info.userAuthInfo.UserId); ctx.WriteAndFlushAsync(info); }); _authorized = true; break; case "authByAndroid": _checkAuth = true; break; case "authByBrowser": _checkAuth = true; break; case "authByIOS": _checkAuth = true; break; case "userAuth": var userAuth = msg.ContentAs <UserAuthPacket>(); _authTask?.Dispose(); _authTask = Task.Factory.StartNew(() => { var authState = _authManager.CheckAuth(userAuth.UserId, userAuth.AuthKey, userAuth.AuthTs, userAuth.IsBrowser); Task.WaitAll(authState); var data = new UserAuthStateRequest { UserAuthState = new UserAuthStateData { State = (int)authState.Result, MinVersion = "0.0.0" } }; InitializeUserHandler(ctx, userAuth.UserId); ctx.WriteAndFlushAsync(data); if (authState.Result == AuthState.Success) { _authorized = true; } }); break; default: _logger.Error("InvalidAuth"); ctx.CloseAsync(); break; } } }
public override Task CloseAsync(IChannelHandlerContext ctx) { log.Info("Channel {0} close", ctx.Channel); return(ctx.CloseAsync()); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { log.Warn($"Exception in NettyClientHandler: {exception.Message}"); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { logger.LogError($"服务端Exception: {exception}"); context.CloseAsync(); }
/// <summary> /// 异常处理 /// </summary> /// <param name="context"></param> /// <param name="exception"></param> public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { _logger.WriteErrorLog(exception); context.CloseAsync(); }
//public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); public override void ExceptionCaught(IChannelHandlerContext context, Exception e) { _channelManager.ExceptionCaught(context, e); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Logger.Error(exception, "Error in clent handler."); context.CloseAsync(); }
public Task CloseAsync(IChannelHandlerContext context) { return(context.CloseAsync()); }
public override Task CloseAsync(IChannelHandlerContext context) { _logger.Debug($"{context.Channel} CLOSE"); return(context.CloseAsync()); }
public override void ChannelRead(IChannelHandlerContext context, object messageData) { var buffer = messageData as IByteBuffer; var data = new byte[0]; if (buffer != null) { data = buffer.ToArray(); } var msg = new CCMessage(data, data.Length); short magic = 0; var message = new ByteArray(); if (msg.Read(ref magic) && magic == Magic && msg.Read(ref message)) { var receivedMessage = new CCMessage(message); CCMessage.MessageType coreId = 0; if (!receivedMessage.Read(ref coreId)) { return; } switch (coreId) { case CCMessage.MessageType.Rmi: short rmiId = 0; if (receivedMessage.Read(ref rmiId)) { switch (rmiId) { case 15: { var username = ""; var password = ""; var register = false; if (receivedMessage.Read(ref username) && receivedMessage.Read(ref password) && receivedMessage.Read(ref register)) { using (var db = AuthDatabase.Open()) { Logger.Information("Authentication login from {endpoint}", context.Channel.RemoteAddress.ToString()); if (username.Length > 5 && password.Length > 5 && Namecheck.IsNameValid(username)) { var result = db.Find <AccountDto>(statement => statement .Where($"{nameof(AccountDto.Username):C} = @{nameof(username)}") .Include <BanDto>(join => @join.LeftOuterJoin()) .WithParameters(new { Username = username })); var account = result.FirstOrDefault(); if (account == null && (Config.Instance.NoobMode || Config.Instance.AutoRegister)) { account = new AccountDto { Username = username }; var newSalt = new byte[24]; using (var csprng = new RNGCryptoServiceProvider()) { csprng.GetBytes(newSalt); } var hash = new Rfc2898DeriveBytes(password, newSalt, 24000).GetBytes(24); account.Password = Convert.ToBase64String(hash); account.Salt = Convert.ToBase64String(newSalt); db.InsertAsync(account); } var salt = Convert.FromBase64String(account?.Salt ?? ""); var passwordGuess = new Rfc2898DeriveBytes(password, salt, 24000).GetBytes(24); var actualPassword = Convert.FromBase64String(account?.Password ?? ""); var difference = (uint)passwordGuess.Length ^ (uint)actualPassword.Length; for (var i = 0; i < passwordGuess.Length && i < actualPassword.Length; i++) { difference |= (uint)(passwordGuess[i] ^ actualPassword[i]); } if ((difference != 0 || string.IsNullOrWhiteSpace(account?.Password ?? "")) && !Config.Instance.NoobMode) { Logger.Error( "Wrong authentication credentials for {username} / {endpoint}", username, context.Channel.RemoteAddress.ToString()); var ack = new CCMessage(); ack.Write(false); ack.Write("Login failed"); RmiSend(context, 16, ack); } else { if (account != null) { account.LoginToken = AuthHash .GetHash256( $"{context.Channel.RemoteAddress}-{account.Username}-{account.Password}") .ToLower(); account.LastLogin = $"{DateTimeOffset.UtcNow:yyyyMMddHHmmss}"; account.AuthToken = ""; account.newToken = ""; db.UpdateAsync(account); var ack = new CCMessage(); ack.Write(true); ack.Write(account.LoginToken); RmiSend(context, 16, ack); } Logger.Information("Authentication success for {username}", username); } } else { Logger.Error( "Wrong authentication credentials for {username} / {endpoint}", username, context.Channel.RemoteAddress.ToString()); var ack = new CCMessage(); ack.Write(false); ack.Write("Invalid length of username/password"); RmiSend(context, 16, ack); } } } else { Logger.Error("Wrong login for {endpoint}", context.Channel.RemoteAddress.ToString()); var ack = new CCMessage(); ack.Write(false); ack.Write("Invalid loginpacket"); RmiSend(context, 16, ack); } break; } case 17: context.CloseAsync(); break; default: Logger.Error("Received unknown rmiId{rmi} from {endpoint}", rmiId, context.Channel.RemoteAddress.ToString()); break; } } break; case CCMessage.MessageType.Notify: context.CloseAsync(); break; default: Logger.Error("Received unknown coreID{coreid} from {endpoint}", coreId, context.Channel.RemoteAddress.ToString()); break; } } else { Logger.Error("Received invalid packetstruct from {endpoint}", context.Channel.RemoteAddress.ToString()); context.CloseAsync(); } }
public override void ExceptionCaught(IChannelHandlerContext context, Exception e) { _logger.LogError(e.Message); context.CloseAsync(); }
public override Task CloseAsync(IChannelHandlerContext ctx) { if (this.Logger.IsEnabled(this.InternalLevel)) { this.Logger.Log(this.InternalLevel, this.Format(ctx, "CLOSE")); } return ctx.CloseAsync(); }
static async void ShutdownOnError(IChannelHandlerContext context, Exception exception) { var self = (MqttIotHubAdapter)context.Handler; if (!self.IsInState(StateFlags.Closed)) { self.stateFlags |= StateFlags.Closed; self.subscribeCompletion?.TrySetException(exception); self.deviceBoundOneWayProcessor.Abort(exception); self.deviceBoundTwoWayProcessor.Abort(exception); self.serviceBoundOneWayProcessor.Abort(exception); self.serviceBoundTwoWayProcessor.Abort(exception); self.onError(exception); try { await context.CloseAsync(); } catch (Exception ex) when (!ex.IsFatal()) { //ignored } } }
async void Shutdown(IChannelHandlerContext context) { if (this.IsInState(StateFlags.Closed)) { return; } try { this.stateFlags |= StateFlags.Closed; // "or" not to interfere with ongoing logic which has to honor Closed state when it's right time to do (case by case) this.CloseIotHubConnection(); await context.CloseAsync(); } catch { // ignored } }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { s_logger.LogError(exception.ToString()); context.CloseAsync(); }
public override void ChannelRead(IChannelHandlerContext context, object message) { while (true) { if (_isWebSocket) { IByteBuffer buffer; _lastReadBuffer?.ResetReaderIndex(); if (_lastReadBuffer != null && _lastReadBuffer.ReadableBytes != 0) { buffer = ByteBufferUtil.DefaultAllocator.Buffer( _lastReadBuffer.ReadableBytes + ((IByteBuffer)message).ReadableBytes); buffer.WriteBytes(_lastReadBuffer); buffer.WriteBytes((IByteBuffer)message); _lastReadBuffer = buffer; } else { buffer = (IByteBuffer)message; _lastReadBuffer = buffer; } if (buffer.ReadableBytes < 2) { return; } IByteBuffer bufferCopy = ByteBufferUtil.DefaultAllocator.Buffer(buffer.Capacity); buffer.ReadBytes(bufferCopy, 2); if ((bufferCopy.GetByte(0) & 8) == 8) { //操作码位8表示断开连接 context.CloseAsync(); return; } byte[] maskKey = { 0, 0, 0, 0 }; bool masked = false; byte lenMark = bufferCopy.GetByte(1); if (lenMark >= 128) { masked = true; lenMark -= 128; } int offset = 0; int len = 0; if (lenMark <= 125) { offset = 2; len = lenMark; } else if (lenMark == 126) { offset = 4; if (buffer.ReadableBytes < 2) { return; } buffer.ReadBytes(bufferCopy, 2); len = bufferCopy.GetUnsignedShort(2); } else if (lenMark == 127) { offset = 10; if (buffer.ReadableBytes < 8) { return; } buffer.ReadBytes(bufferCopy, 8); len = (int)bufferCopy.GetLong(2); } if (masked) { if (buffer.ReadableBytes < 4) { return; } buffer.ReadBytes(bufferCopy, 4); for (int i = 0; i < 4; i++) { maskKey[i] = bufferCopy.GetByte(offset + i); } offset += 4; } if (buffer.ReadableBytes < len) { return; } buffer.ReadBytes(bufferCopy, len); IByteBuffer output = ByteBufferUtil.DefaultAllocator.Buffer(len); for (int i = 0; i < len; i++) { output.WriteByte(bufferCopy.GetByte(offset + i) ^ maskKey[i % 4]); } _lastReadBuffer.MarkReaderIndex(); base.ChannelRead(context, output); if (_lastReadBuffer.ReadableBytes <= 0) { return; } _lastReadBuffer = null; message = buffer; continue; } try { var buffer = (IByteBuffer)message; IByteBuffer bufferCopy = buffer.Copy(); var bytes = new byte[bufferCopy.ReadableBytes]; bufferCopy.ReadBytes(bytes); string data = Encoding.ASCII.GetString(bytes); const string requestWebSocketMark = "Sec-WebSocket-Key:"; int index = data.IndexOf(requestWebSocketMark, StringComparison.Ordinal); if (index < 0) { throw new Exception(); } data = data.Substring(index + requestWebSocketMark.Length + 1); var key = new StringBuilder(); foreach (char t in data) { if (IsBase64Char(t)) { key.Append(t); } else { break; } } key.Append("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); SHA1 sha1 = new SHA1CryptoServiceProvider(); data = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(key.ToString()))); sha1.Dispose(); StringBuilder ret = new StringBuilder(); ret.Append("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "); ret.Append(data); ret.Append("\r\nUpgrade: websocket\r\n\r\n"); IByteBuffer output = ByteBufferUtil.DefaultAllocator.Buffer(); output.WriteBytes(Encoding.UTF8.GetBytes(ret.ToString())); context.WriteAndFlushAsync(output); _isWebSocket = true; } catch { base.ChannelRead(context, message); } finally { if (_isWebSocket) { context.Channel.Pipeline.Remove <LengthFieldBasedFrameDecoder>(); context.Channel.Pipeline.Remove <LengthFieldPrepender>(); } else { context.Channel.Pipeline.Remove(this); } } break; } }
/// <summary> /// Closes channel /// </summary> /// <param name="context"></param> /// <param name="graceful"></param> async void Shutdown(IChannelHandlerContext context, bool graceful) { if (this.IsInState(StateFlags.Closed)) { return; } try { this.stateFlags |= StateFlags.Closed; // "or" not to interfere with ongoing logic which has to honor Closed state when it's right time to do (case by case) PerformanceCounters.ConnectionsCurrent.Decrement(); Queue<Packet> connectQueue = this.connectPendingQueue; if (connectQueue != null) { while (connectQueue.Count > 0) { Packet packet = connectQueue.Dequeue(); ReferenceCountUtil.Release(packet); } } PublishPacket will = !graceful && this.IsInState(StateFlags.Connected) ? this.willPacket : null; if (will != null) { // try publishing will message before shutting down IoT Hub connection try { this.publishProcessor.Post(context, will); } catch (Exception ex) { MqttIotHubAdapterEventSource.Log.Warning("Failed sending Will Message.", ex); } } this.CloseIotHubConnection(); await context.CloseAsync(); } catch (Exception ex) { MqttIotHubAdapterEventSource.Log.Warning("Error occurred while shutting down the channel.", ex); } }
public override void ExceptionCaught(IChannelHandlerContext contex, Exception e) { Console.WriteLine(DateTime.Now.Millisecond); Console.WriteLine(e.StackTrace); contex.CloseAsync(); }
//--------------------------------------------------------------------- public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { _logger.Error("Exception: " + exception, exception); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { this.completion.TrySetException(exception); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) => context.CloseAsync();
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Console.WriteLine("Exception: " + exception); context.CloseAsync(); }
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception exception) { OnException?.Invoke(exception); completionSource.TrySetException(exception); ctx.CloseAsync(); }
public virtual Task CloseAsync(IChannelHandlerContext context) => context.CloseAsync();
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause) { //Logger.Warn("Failed to initialize a channel. Closing: " + ctx.Channel, cause); ctx.CloseAsync(); }