Search in sources :

Example 16 with TooLongFrameException

use of io.netty.handler.codec.TooLongFrameException in project graylog2-server by Graylog2.

the class LenientDelimiterBasedFrameDecoderTest method testFailFastTooLongFrameRecovery.

@Test
public void testFailFastTooLongFrameRecovery() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new LenientDelimiterBasedFrameDecoder(1, Delimiters.nulDelimiter()));
    for (int i = 0; i < 2; i++) {
        try {
            assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 1, 2 })));
            fail(DecoderException.class.getSimpleName() + " must be raised.");
        } catch (TooLongFrameException e) {
        // Expected
        }
        ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 'A', 0 }));
        ByteBuf buf = ch.readInbound();
        assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1));
        buf.release();
    }
}
Also used : TooLongFrameException(io.netty.handler.codec.TooLongFrameException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 17 with TooLongFrameException

use of io.netty.handler.codec.TooLongFrameException in project rest.li by linkedin.

the class StreamWriter method onDataAvailable.

/**
 * Notifies the writer that bytes are available from the {@link ChannelPipeline}.
 * @param data Available bytes from the channel pipeline.
 */
public void onDataAvailable(ByteString data) {
    if (data.length() + _totalBytesWritten > _maxContentLength) {
        onError(new TooLongFrameException("HTTP content length exceeded " + _maxContentLength + " bytes."));
        return;
    }
    _totalBytesWritten += data.length();
    _buffer.add(data);
    _bufferedBytes += data.length();
    if (_bufferedBytes > BUFFER_HIGH_WATER_MARK && _ctx.channel().config().isAutoRead()) {
        _ctx.channel().config().setAutoRead(false);
    }
    if (_wh != null) {
        doWrite();
    }
}
Also used : TooLongFrameException(io.netty.handler.codec.TooLongFrameException)

Example 18 with TooLongFrameException

use of io.netty.handler.codec.TooLongFrameException in project BRFS by zhangnianli.

the class JsonBytesDecoder method decode.

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (state == ST_CORRUPTED) {
        in.skipBytes(in.readableBytes());
        return;
    }
    // index of next byte to process.
    int idx = in.readerIndex() + this.indexOffset;
    int wrtIdx = in.writerIndex();
    for (; /* use current idx */
    idx < wrtIdx; idx++) {
        byte c = in.getByte(idx);
        if (state == ST_DECODING_NORMAL) {
            decodeByte(c, in, idx);
            // that the JSON object/array is complete.
            if (openBraces == 0) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }
                // The JSON object/array was extracted => discard the bytes from
                // the input buffer.
                in.readerIndex(idx + 1);
                // Reset the object state to get ready for the next JSON object/text
                // coming along the byte stream.
                reset();
            }
        } else if (state == ST_DECODING_ARRAY_STREAM) {
            decodeByte(c, in, idx);
            if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
                // because the byte at position idx is not a whitespace.
                for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
                    in.skipBytes(1);
                }
                // skip trailing spaces.
                int idxNoSpaces = idx - 1;
                while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) {
                    idxNoSpaces--;
                }
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }
                in.readerIndex(idx + 1);
                if (c == ']') {
                    reset();
                }
            }
        // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
        } else if (c == '{' || c == '[') {
            initDecoding(c);
            if (state == ST_DECODING_ARRAY_STREAM) {
                // Discard the array bracket
                in.skipBytes(1);
            }
        // Discard leading spaces in front of a JSON object/array.
        } else if (Character.isWhitespace(c)) {
            in.skipBytes(1);
        } else {
            state = ST_CORRUPTED;
            throw new CorruptedFrameException("invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in));
        }
    }
    if (in.readableBytes() == 0) {
        this.indexOffset = 0;
    } else {
        if (in.readableBytes() > maxObjectLength) {
            // buffer size exceeded maxObjectLength; discarding the complete buffer.
            in.skipBytes(in.readableBytes());
            reset();
            throw new TooLongFrameException("object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded");
        }
        this.indexOffset = idx - in.readerIndex();
    }
}
Also used : TooLongFrameException(io.netty.handler.codec.TooLongFrameException) CorruptedFrameException(io.netty.handler.codec.CorruptedFrameException) ByteBuf(io.netty.buffer.ByteBuf)

Example 19 with TooLongFrameException

use of io.netty.handler.codec.TooLongFrameException in project riposte by Nike-Inc.

the class BackstopperRiposteFrameworkErrorHandlerListenerTest method shouldHandleInvalidHttpRequestExceptionWithNonNullCause.

@DataProvider(value = { "true", "false" })
@Test
public void shouldHandleInvalidHttpRequestExceptionWithNonNullCause(boolean useTooLongFrameExceptionAsCause) {
    // given
    Throwable cause = (useTooLongFrameExceptionAsCause) ? new TooLongFrameException("TooLongFrameException occurred") : new RuntimeException("runtime exception");
    String expectedCauseMetadataMessage = (useTooLongFrameExceptionAsCause) ? listener.TOO_LONG_FRAME_LINE_METADATA_MESSAGE : "Invalid HTTP request";
    String outerExceptionMessage = "message - " + UUID.randomUUID().toString();
    ApiError expectedApiErrorBase = (useTooLongFrameExceptionAsCause) ? listener.TOO_LONG_FRAME_LINE_API_ERROR_BASE : testProjectApiErrors.getMalformedRequestApiError();
    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(new InvalidHttpRequestException(outerExceptionMessage, cause));
    // then
    assertThat(result.shouldHandleResponse).isTrue();
    assertThat(result.errors).isEqualTo(singletonError(new ApiErrorWithMetadata(expectedApiErrorBase, Pair.of("cause", expectedCauseMetadataMessage))));
    assertThat(result.extraDetailsForLogging.get(0).getLeft()).isEqualTo("exception_message");
    assertThat(result.extraDetailsForLogging.get(0).getRight()).isEqualTo(outerExceptionMessage);
    assertThat(result.extraDetailsForLogging.get(1).getLeft()).isEqualTo("exception_cause_details");
    assertThat(result.extraDetailsForLogging.get(1).getRight()).isEqualTo(cause.toString());
}
Also used : TooLongFrameException(io.netty.handler.codec.TooLongFrameException) ApiErrorWithMetadata(com.nike.backstopper.apierror.ApiErrorWithMetadata) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) ApiError(com.nike.backstopper.apierror.ApiError) InvalidHttpRequestException(com.nike.riposte.server.error.exception.InvalidHttpRequestException) ApiExceptionHandlerListenerResult(com.nike.backstopper.handler.listener.ApiExceptionHandlerListenerResult) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) Test(org.junit.Test)

Example 20 with TooLongFrameException

use of io.netty.handler.codec.TooLongFrameException in project vert.x by eclipse.

the class ServerConnection method processMessage.

private void processMessage(Object msg) {
    if (msg instanceof HttpObject) {
        HttpObject obj = (HttpObject) msg;
        DecoderResult result = obj.decoderResult();
        if (result.isFailure()) {
            Throwable cause = result.cause();
            if (cause instanceof TooLongFrameException) {
                String causeMsg = cause.getMessage();
                HttpVersion version;
                if (msg instanceof HttpRequest) {
                    version = ((HttpRequest) msg).protocolVersion();
                } else if (currentRequest != null) {
                    version = currentRequest.version() == io.vertx.core.http.HttpVersion.HTTP_1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
                } else {
                    version = HttpVersion.HTTP_1_1;
                }
                HttpResponseStatus status = causeMsg.startsWith("An HTTP line is larger than") ? HttpResponseStatus.REQUEST_URI_TOO_LONG : HttpResponseStatus.BAD_REQUEST;
                DefaultFullHttpResponse resp = new DefaultFullHttpResponse(version, status);
                writeToChannel(resp);
            }
            // That will close the connection as it is considered as unusable
            channel.pipeline().fireExceptionCaught(result.cause());
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            if (server.options().isHandle100ContinueAutomatically()) {
                if (HttpHeaders.is100ContinueExpected(request)) {
                    write100Continue();
                }
            }
            HttpServerResponseImpl resp = new HttpServerResponseImpl(vertx, this, request);
            HttpServerRequestImpl req = new HttpServerRequestImpl(this, request, resp);
            handleRequest(req, resp);
        }
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            if (chunk.content().isReadable()) {
                Buffer buff = Buffer.buffer(chunk.content());
                handleChunk(buff);
            }
            //TODO chunk trailers
            if (msg instanceof LastHttpContent) {
                if (!paused) {
                    handleEnd();
                } else {
                    // Requeue
                    pending.add(LastHttpContent.EMPTY_LAST_CONTENT);
                }
            }
        }
    } else if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        handleWsFrame(frame);
    }
    checkNextTick();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) WebSocketFrameInternal(io.vertx.core.http.impl.ws.WebSocketFrameInternal) DecoderResult(io.netty.handler.codec.DecoderResult) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Aggregations

TooLongFrameException (io.netty.handler.codec.TooLongFrameException)31 ByteBuf (io.netty.buffer.ByteBuf)15 Test (org.junit.Test)9 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)7 Channel (io.netty.channel.Channel)5 Buffer (io.vertx.core.buffer.Buffer)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 CorruptedFrameException (io.netty.handler.codec.CorruptedFrameException)4 TestUtils (io.vertx.test.core.TestUtils)4 java.util (java.util)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 Test (org.junit.jupiter.api.Test)4 ChannelHandler (io.netty.channel.ChannelHandler)2 EventLoop (io.netty.channel.EventLoop)2 DecoderException (io.netty.handler.codec.DecoderException)2 DelimiterBasedFrameDecoder (io.netty.handler.codec.DelimiterBasedFrameDecoder)2 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)2 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)2 io.vertx.core (io.vertx.core)2 Future (io.vertx.core.Future)2