public override void ChannelRead(IChannelHandlerContext ctx, object msg) { if (msg is IHttp2DataFrame data) { var f = ctx.WriteAndFlushAsync(new DefaultHttp2WindowUpdateFrame(data.InitialFlowControlledBytes) { Stream = data.Stream }); f.ContinueWith(t => { if (t.IsFaulted) { ctx.FireExceptionCaught(t.Exception.InnerException); } }, TaskContinuationOptions.ExecuteSynchronously); } ReferenceCountUtil.Release(msg); }
void InvokeHandleOversizedMessage(IChannelHandlerContext context, BulkStringHeaderRedisMessage startMessage) { Contract.Requires(context != null); Contract.Requires(startMessage != null); this.currentMessage = null; try { context.FireExceptionCaught( new TooLongFrameException($"Content length exceeded {this.maximumContentLength} bytes.")); } finally { // Release the message in case it is a full one. ReferenceCountUtil.Release(startMessage); } }
public void Run() { // Was not written yet so issue a write timeout // The future itself will be failed with a ClosedChannelException once the close() was issued // See https://github.com/netty/netty/issues/2159 if (!_future.IsCompleted) { try { _handler.WriteTimedOut(_context); } catch (Exception ex) { _ = _context.FireExceptionCaught(ex); } } _handler.RemoveWriteTimeoutTask(this); }
private static Task SendA(IChannelHandlerContext ctx, CCMessage data) { var coreframe = new CCMessage(); coreframe.Write(Magic); coreframe.WriteScalar(data.Length); coreframe.Write(data); var buffer = Unpooled.Buffer(coreframe.Length); buffer.WriteBytes(coreframe.Buffer); try { ctx.WriteAndFlushAsync(buffer).WaitEx(); } catch (Exception e) { ctx.FireExceptionCaught(e); } return Task.CompletedTask; }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { if (Logger.WarnEnabled) { Logger.Warn($"Channel {context.Channel} caught exception", exception); } switch (exception) { case SocketException se when se.SocketErrorCode.IsSocketAbortError(): case OperationException oe when oe.ErrorCode.IsConnectionAbortError(): case ChannelException ce when(ce.InnerException is OperationException exc && exc.ErrorCode.IsConnectionAbortError()): DoBind(); break; default: context.FireExceptionCaught(exception); break; } }
static void HandleAllTimeout(IdleStateHandler self, IChannelHandlerContext context) { TimeSpan nextDelay = self._allIdleTime; if (!self._reading) { nextDelay -= self.Ticks() - TimeUtil.Max(self._lastReadTime, self._lastWriteTime); } if (nextDelay.Ticks <= 0) { // Both reader and writer are idle - set a new timeout and // notify the callback. self._allIdleTimeout = self.Schedule(context, AllTimeoutAction, self, context, self._allIdleTime); bool first = self._firstAllIdleEvent; self._firstAllIdleEvent = false; try { if (self.HasOutputChanged(context, first)) { return; } IdleStateEvent stateEvent = self.NewIdleStateEvent(IdleState.AllIdle, first); self.ChannelIdle(context, stateEvent); } catch (Exception ex) { _ = context.FireExceptionCaught(ex); } } else { // Either read or write occurred before the timeout - set a new // timeout with shorter delay. self._allIdleTimeout = self.Schedule(context, AllTimeoutAction, self, context, nextDelay); } }
protected override IByteBuffer Encode(IChannelHandlerContext context, ThriftMessage message) { int frameSize = message.Buffer.ReadableBytes; if (message.Buffer.ReadableBytes > _maxFrameSize) { context.FireExceptionCaught(new TooLongFrameException( String.Format( "Frame size exceeded on encode: frame was {0:d} bytes, maximum allowed is {1:d} bytes", frameSize, _maxFrameSize))); return(null); } switch (message.TransportType) { case ThriftTransportType.Unframed: return(message.Buffer); case ThriftTransportType.Framed: var buffer = Unpooled.Buffer(4 + message.Buffer.ReadableBytes, 4 + message.Buffer.ReadableBytes); buffer.WriteInt(message.Buffer.ReadableBytes); buffer.WriteBytes(message.Buffer, message.Buffer.ReadableBytes); return(buffer); //return Buffers.WrappedBuffer(context.Allocator, buffer, message.Buffer); case ThriftTransportType.Header: throw new NotSupportedException("Header transport is not supported"); case ThriftTransportType.Http: throw new NotSupportedException("HTTP transport is not supported"); default: throw new NotSupportedException("Unrecognized transport type"); } }
//static Action<object, object> WrapperTimeoutHandler(Action<IdleStateHandler, IChannelHandlerContext> action) //{ // return (handler, ctx) => // { // var self = (IdleStateHandler)handler; // instead of this // var context = (IChannelHandlerContext)ctx; // if (!context.Channel.Open) // { // return; // } // action(self, context); // }; //} static void HandleReadTimeout(IdleStateHandler self, IChannelHandlerContext context) { TimeSpan nextDelay = self._readerIdleTime; if (!self._reading) { nextDelay -= self.Ticks() - self._lastReadTime; } if (nextDelay.Ticks <= 0) { // Reader is idle - set a new timeout and notify the callback. self._readerIdleTimeout = self.Schedule(context, ReadTimeoutAction, self, context, self._readerIdleTime); bool first = self._firstReaderIdleEvent; self._firstReaderIdleEvent = false; try { IdleStateEvent stateEvent = self.NewIdleStateEvent(IdleState.ReaderIdle, first); self.ChannelIdle(context, stateEvent); } catch (Exception ex) { _ = context.FireExceptionCaught(ex); } } else { // Read occurred before the timeout - set a new timeout with shorter delay. self._readerIdleTimeout = self.Schedule(context, ReadTimeoutAction, self, context, nextDelay); } }
public void UpgradeTo(IChannelHandlerContext ctx, IFullHttpResponse upgradeResponse) { try { // Add the handler to the pipeline. _ = ctx.Pipeline.AddAfter(ctx.Name, _handlerName, _upgradeToHandler); // Add the Http2 Multiplex handler as this handler handle events produced by the connectionHandler. // See https://github.com/netty/netty/issues/9495 if (_http2MultiplexHandler is object) { var name = ctx.Pipeline.Context(_connectionHandler).Name; _ = ctx.Pipeline.AddAfter(name, null, _http2MultiplexHandler); } // Reserve local stream 1 for the response. _connectionHandler.OnHttpClientUpgrade(); } catch (Http2Exception e) { _ = ctx.FireExceptionCaught(e); _ = ctx.CloseAsync(); } }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="exception"></param> public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { context.FireExceptionCaught(exception); }
void Fail(IChannelHandlerContext ctx, string length) { ctx.FireExceptionCaught( new TooLongFrameException( $"frame length ({length}) exceeds the allowed maximum ({this.maxLength})")); }
protected internal override void Decode(IChannelHandlerContext context, IHttpObject message, List <object> output) { IFullHttpResponse response = null; try { if (!this.upgradeRequested) { throw new InvalidOperationException("Read HTTP response without requesting protocol switch"); } if (message is IHttpResponse rep) { if (!HttpResponseStatus.SwitchingProtocols.Equals(rep.Status)) { // The server does not support the requested protocol, just remove this handler // and continue processing HTTP. // NOTE: not releasing the response since we're letting it propagate to the // next handler. context.FireUserEventTriggered(UpgradeEvent.UpgradeRejected); RemoveThisHandler(context); context.FireChannelRead(rep); return; } } if (message is IFullHttpResponse fullRep) { response = fullRep; // Need to retain since the base class will release after returning from this method. response.Retain(); output.Add(response); } else { // Call the base class to handle the aggregation of the full request. base.Decode(context, message, output); if (output.Count == 0) { // The full request hasn't been created yet, still awaiting more data. return; } Debug.Assert(output.Count == 1); response = (IFullHttpResponse)output[0]; } if (response.Headers.TryGet(HttpHeaderNames.Upgrade, out ICharSequence upgradeHeader) && !AsciiString.ContentEqualsIgnoreCase(this.upgradeCodec.Protocol, upgradeHeader)) { throw new InvalidOperationException($"Switching Protocols response with unexpected UPGRADE protocol: {upgradeHeader}"); } // Upgrade to the new protocol. this.sourceCodec.PrepareUpgradeFrom(context); this.upgradeCodec.UpgradeTo(context, response); // Notify that the upgrade to the new protocol completed successfully. context.FireUserEventTriggered(UpgradeEvent.UpgradeSuccessful); // We guarantee UPGRADE_SUCCESSFUL event will be arrived at the next handler // before http2 setting frame and http response. this.sourceCodec.UpgradeFrom(context); // We switched protocols, so we're done with the upgrade response. // Release it and clear it from the output. response.Release(); output.Clear(); RemoveThisHandler(context); } catch (Exception exception) { ReferenceCountUtil.Release(response); context.FireExceptionCaught(exception); RemoveThisHandler(context); } }
public virtual void ExceptionCaught(IChannelHandlerContext context, Exception exception) => context.FireExceptionCaught(exception);
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause) { Logger().LogError(cause, $"Channel {ctx.Channel} caught exception"); ctx.FireExceptionCaught(cause); }
public void ExceptionCaught(IChannelHandlerContext ctx, Exception exception) => ctx.FireExceptionCaught(exception);
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause) { _log.Error(cause, "Channel {0} caught exception", ctx.Channel); ctx.FireExceptionCaught(cause); }
protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output) { int startOffset = input.ReaderIndex; int endOffset = input.WriterIndex; int offset = startOffset; int totalLength = 0; List <int> packetLengths; // if we calculated the length of the current SSL record before, use that information. if (_packetLength > 0) { if (endOffset - startOffset < _packetLength) { // input does not contain a single complete SSL record return; } else { packetLengths = new List <int>(4) { _packetLength }; offset += _packetLength; totalLength = _packetLength; _packetLength = 0; } } else { packetLengths = new List <int>(4); } bool nonSslRecord = false; while (totalLength < TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { int readableBytes = endOffset - offset; if (readableBytes < TlsUtils.SSL_RECORD_HEADER_LENGTH) { break; } int encryptedPacketLength = TlsUtils.GetEncryptedPacketLength(input, offset); if (encryptedPacketLength == TlsUtils.NOT_ENCRYPTED) { nonSslRecord = true; break; } Debug.Assert(encryptedPacketLength > 0); if (encryptedPacketLength > readableBytes) { // wait until the whole packet can be read _packetLength = encryptedPacketLength; break; } int newTotalLength = totalLength + encryptedPacketLength; if (newTotalLength > TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { // Don't read too much. break; } // 1. call unwrap with packet boundaries - call SslStream.ReadAsync only once. // 2. once we're through all the whole packets, switch to reading out using fallback sized buffer // We have a whole packet. // Increment the offset to handle the next packet. packetLengths.Add(encryptedPacketLength); offset += encryptedPacketLength; totalLength = newTotalLength; } if (totalLength > 0) { // The buffer contains one or more full SSL records. // Slice out the whole packet so unwrap will only be called with complete packets. // Also directly reset the packetLength. This is needed as unwrap(..) may trigger // decode(...) again via: // 1) unwrap(..) is called // 2) wrap(...) is called from within unwrap(...) // 3) wrap(...) calls unwrapLater(...) // 4) unwrapLater(...) calls decode(...) // // See https://github.com/netty/netty/issues/1534 _ = input.SkipBytes(totalLength); try { Unwrap(context, input, startOffset, totalLength, packetLengths, output); if (!_firedChannelRead) { // Check first if firedChannelRead is not set yet as it may have been set in a // previous decode(...) call. _firedChannelRead = (uint)output.Count > 0u; } } catch (Exception cause) { try { // We need to flush one time as there may be an alert that we should send to the remote peer because // of the SSLException reported here. WrapAndFlush(context); } // TODO revisit //catch (IOException) //{ // if (s_logger.DebugEnabled) // { // s_logger.Debug("SSLException during trying to call SSLEngine.wrap(...)" + // " because of an previous SSLException, ignoring...", ex); // } //} finally { HandleFailure(cause); } ExceptionDispatchInfo.Capture(cause).Throw(); } } if (nonSslRecord) { // Not an SSL/TLS packet var ex = GetNotSslRecordException(input); _ = input.SkipBytes(input.ReadableBytes); // First fail the handshake promise as we may need to have access to the SSLEngine which may // be released because the user will remove the SslHandler in an exceptionCaught(...) implementation. HandleFailure(ex); _ = context.FireExceptionCaught(ex); } }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Assert.Same(_exception, exception); _queue.Enqueue(this); context.FireExceptionCaught(exception); }
/// <summary> /// Is called when a read timeout was detected. /// </summary> /// <param name="context">Context.</param> protected virtual void ReadTimedOut(IChannelHandlerContext context) { if(!this.closed) { context.FireExceptionCaught(ReadTimeoutException.Instance); context.Flush(); this.closed = true; } }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { _logger.Debug($"{context.Channel} EXCEPTION: {exception}"); context.FireExceptionCaught(exception); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { Log.Debug($"{context.Name}: ExceptionCaught {exception}"); context.FireExceptionCaught(exception); }
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause) { if (this.Logger.IsEnabled(this.InternalLevel)) { this.Logger.Log(this.InternalLevel, this.Format(ctx, "EXCEPTION", cause), cause); } ctx.FireExceptionCaught(cause); }
protected virtual object Decode(IChannelHandlerContext ctx, IByteBuffer buffer) { buffer.MarkReaderIndex(); try { TMessage message = new TMessage(); int size = buffer.ReadInt(); if (size < 0) { uint version = (uint)size & VERSION_MASK; if (version != VERSION_1) { Trace.WriteLine($"Bad version in ReadMessageBegin: {version}"); buffer.SetReaderIndex(buffer.WriterIndex); ctx.FireExceptionCaught( new ThriftDecoderException($"Bad version in ReadMessageBegin: {version}")); return(null); } message.Type = (Thrift.Protocol.TMessageType)(size & 0x000000ff); message.Name = this.ReadString(buffer); message.SeqID = buffer.ReadInt(); } else { if (this.StrictRead) { ctx.FireExceptionCaught( new ThriftDecoderException("Missing version in readMessageBegin, old client?")); } message.Name = this.ReadStringBody(buffer, size); message.Type = (Thrift.Protocol.TMessageType)buffer.ReadByte(); message.SeqID = buffer.ReadInt(); } var messageSize = buffer.ReaderIndex; buffer.MarkReaderIndex(); var len = GetTypeSize(buffer, TType.Struct); if (len >= 0) { IByteBuffer frame; if (len > this.MaxFrameSize) { buffer.SetReaderIndex(len); ctx.FireExceptionCaught( new ThriftDecoderException(new TooLongFrameException($"frame length ({len}) exceeds the allowed maximum ({this.MaxFrameSize})"))); return(null); } buffer.SetReaderIndex(0); frame = buffer.ReadSlice(messageSize + len); frame.Retain(); return(new FrameThriftMessage(ThriftTransportType.Framed, frame)); //return frame.Retain(); } else { buffer.SetReaderIndex(0); return(null); } } catch (Exception ex) { Trace.WriteLine(ex.Message); if (buffer.ReadableBytes < 1024) { buffer.ResetReaderIndex(); return(null); } else { Trace.WriteLine($"Bad Message Format in ReadMessageBegin"); buffer.SetReaderIndex(buffer.WriterIndex); ctx.FireExceptionCaught( new ThriftDecoderException($"Bad Message Format in ReadMessageBegin")); return(null); } } }
protected internal override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output) { int startOffset = input.ReaderIndex; int endOffset = input.WriterIndex; int offset = startOffset; int totalLength = 0; List <int> packetLengths; // if we calculated the length of the current SSL record before, use that information. if (this.packetLength > 0) { if (endOffset - startOffset < this.packetLength) { // input does not contain a single complete SSL record return; } else { packetLengths = new List <int>(4); packetLengths.Add(this.packetLength); offset += this.packetLength; totalLength = this.packetLength; this.packetLength = 0; } } else { packetLengths = new List <int>(4); } bool nonSslRecord = false; while (totalLength < TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { int readableBytes = endOffset - offset; if (readableBytes < TlsUtils.SSL_RECORD_HEADER_LENGTH) { break; } int encryptedPacketLength = TlsUtils.GetEncryptedPacketLength(input, offset); if (encryptedPacketLength == -1) { nonSslRecord = true; break; } Contract.Assert(encryptedPacketLength > 0); if (encryptedPacketLength > readableBytes) { // wait until the whole packet can be read this.packetLength = encryptedPacketLength; break; } int newTotalLength = totalLength + encryptedPacketLength; if (newTotalLength > TlsUtils.MAX_ENCRYPTED_PACKET_LENGTH) { // Don't read too much. break; } // 1. call unwrap with packet boundaries - call SslStream.ReadAsync only once. // 2. once we're through all the whole packets, switch to reading out using fallback sized buffer // We have a whole packet. // Increment the offset to handle the next packet. packetLengths.Add(encryptedPacketLength); offset += encryptedPacketLength; totalLength = newTotalLength; } if (totalLength > 0) { // The buffer contains one or more full SSL records. // Slice out the whole packet so unwrap will only be called with complete packets. // Also directly reset the packetLength. This is needed as unwrap(..) may trigger // decode(...) again via: // 1) unwrap(..) is called // 2) wrap(...) is called from within unwrap(...) // 3) wrap(...) calls unwrapLater(...) // 4) unwrapLater(...) calls decode(...) // // See https://github.com/netty/netty/issues/1534 input.SkipBytes(totalLength); this.Unwrap(context, input, startOffset, totalLength, packetLengths, output); if (!this.firedChannelRead) { // Check first if firedChannelRead is not set yet as it may have been set in a // previous decode(...) call. this.firedChannelRead = output.Count > 0; } } if (nonSslRecord) { // Not an SSL/TLS packet var ex = new NotSslRecordException( "not an SSL/TLS record: " + ByteBufferUtil.HexDump(input)); input.SkipBytes(input.ReadableBytes); context.FireExceptionCaught(ex); this.HandleFailure(ex); } }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { RegisterFiredEvent(SupportedEvent.ExceptionCaught); context.FireExceptionCaught(exception); }
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause) { ctx.FireExceptionCaught(cause); ctx.CloseAsync(); }
private void OnDispatchException(IChannelHandlerContext ctx, Exception t) { ctx.FireExceptionCaught(t); this.CloseChannel(ctx); }
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { // To ensure we not miss to flush anything, do it now. ResetReadAndFlushIfNeeded(context); context.FireExceptionCaught(exception); }
public override void ChannelInactive(IChannelHandlerContext context) { context.FireExceptionCaught(new DecoderException("CleanupThrows")); context.FireChannelInactive(); }
void Fail(IChannelHandlerContext ctx, string length) { _ = ctx.FireExceptionCaught( new TooLongFrameException( $"frame length ({length}) exceeds the allowed maximum ({this.maxLength})")); }
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception cause) { // To ensure we not miss to flush anything, do it now. ResetReadAndFlushIfNeeded(ctx); _ = ctx.FireExceptionCaught(cause); }