List of usage examples for io.netty.handler.codec TooLongFrameException TooLongFrameException
public TooLongFrameException(Throwable cause)
From source file:cloudeventbus.codec.Decoder.java
License:Open Source License
@Override public Frame decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { in.markReaderIndex();//w w w .j a v a2 s . c o m final int frameLength = indexOf(in, Codec.DELIMITER); // Frame hasn't been fully read yet. if (frameLength < 0) { if (in.readableBytes() > maxMessageSize) { throw new TooLongFrameException("Frame exceeds maximum size"); } in.resetReaderIndex(); return null; } // Empty frame, discard and continue decoding if (frameLength == 0) { in.skipBytes(Codec.DELIMITER.length); return decode(ctx, in); } if (frameLength > maxMessageSize) { throw new TooLongFrameException("Frame exceeds maximum size"); } final String command = in.readBytes(frameLength).toString(CharsetUtil.UTF_8); in.skipBytes(Codec.DELIMITER.length); final String[] parts = command.split("\\s+"); final char frameTypeChar = parts[0].charAt(0); final FrameType frameType = FrameType.getFrameType(frameTypeChar); if (frameType == null) { throw new DecodingException("Invalid frame type " + frameTypeChar); } LOGGER.debug("Decoding frame of type {}", frameType); final int argumentsLength = parts.length - 1; switch (frameType) { case AUTH_RESPONSE: assertArgumentsLength(3, argumentsLength, "authentication response"); final CertificateChain certificates = new CertificateChain(); final byte[] rawCertificates = Base64.decodeBase64(parts[1].getBytes()); CertificateStoreLoader.load(new ByteArrayInputStream(rawCertificates), certificates); final byte[] salt = Base64.decodeBase64(parts[2]); final byte[] digitalSignature = Base64.decodeBase64(parts[3]); return new AuthenticationResponseFrame(certificates, salt, digitalSignature); case AUTHENTICATE: assertArgumentsLength(1, argumentsLength, "authentication request"); final byte[] challenge = Base64.decodeBase64(parts[1]); return new AuthenticationRequestFrame(challenge); case ERROR: if (parts.length == 0) { throw new DecodingException("Error is missing error code"); } final Integer errorNumber = Integer.valueOf(parts[1]); final ErrorFrame.Code errorCode = ErrorFrame.Code.lookupCode(errorNumber); int messageIndex = 1; messageIndex = skipWhiteSpace(messageIndex, command); while (messageIndex < command.length() && Character.isDigit(command.charAt(messageIndex))) { messageIndex++; } messageIndex = skipWhiteSpace(messageIndex, command); final String errorMessage = command.substring(messageIndex).trim(); if (errorMessage.length() > 0) { return new ErrorFrame(errorCode, errorMessage); } else { return new ErrorFrame(errorCode); } case GREETING: assertArgumentsLength(3, argumentsLength, "greeting"); final int version = Integer.valueOf(parts[1]); final String agent = parts[2]; final long id = Long.valueOf(parts[3]); return new GreetingFrame(version, agent, id); case PING: return PingFrame.PING; case PONG: return PongFrame.PONG; case PUBLISH: if (argumentsLength < 2 || argumentsLength > 3) { throw new DecodingException( "Expected message frame to have 2 or 3 arguments. It has " + argumentsLength + "."); } final String messageSubject = parts[1]; final String replySubject; final Integer messageLength; if (parts.length == 3) { replySubject = null; messageLength = Integer.valueOf(parts[2]); } else { replySubject = parts[2]; messageLength = Integer.valueOf(parts[3]); } if (in.readableBytes() < messageLength + Codec.DELIMITER.length) { // If we haven't received the entire message body (plus the CRLF), wait until it arrives. in.resetReaderIndex(); return null; } final ByteBuf messageBytes = in.readBytes(messageLength); final String messageBody = new String(messageBytes.array(), CharsetUtil.UTF_8); in.skipBytes(Codec.DELIMITER.length); // Ignore the CRLF after the message body. return new PublishFrame(new Subject(messageSubject), replySubject == null ? null : new Subject(replySubject), messageBody); case SERVER_READY: return ServerReadyFrame.SERVER_READY; case SUBSCRIBE: assertArgumentsLength(1, argumentsLength, "subscribe"); return new SubscribeFrame(new Subject(parts[1])); case UNSUBSCRIBE: assertArgumentsLength(1, argumentsLength, "unsubscribe"); return new UnsubscribeFrame(new Subject(parts[1])); default: throw new DecodingException("Unknown frame type " + frameType); } }
From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { AggregatedFullHttpMessage currentMessage = this.currentMessage; if (msg instanceof HttpMessage) { tooLongFrameFound = false;/*from w w w. ja v a2 s . c om*/ assert currentMessage == null; HttpMessage m = (HttpMessage) msg; // Handle the 'Expect: 100-continue' header if necessary. if (is100ContinueExpected(m)) { if (HttpHeaders.getContentLength(m, 0) > maxContentLength) { tooLongFrameFound = true; final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain()); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); if (closeOnExpectationFailed) { future.addListener(ChannelFutureListener.CLOSE); } ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE); return; } ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); } if (!m.getDecoderResult().isSuccess()) { removeTransferEncodingChunked(m); out.add(toFullMessage(m)); this.currentMessage = null; return; } if (msg instanceof HttpRequest) { HttpRequest header = (HttpRequest) msg; this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header, ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null); } else if (msg instanceof HttpResponse) { HttpResponse header = (HttpResponse) msg; this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header, Unpooled.compositeBuffer(maxCumulationBufferComponents), null); } else { throw new Error(); } // A streamed message - initialize the cumulative buffer, and wait for incoming chunks. removeTransferEncodingChunked(currentMessage); } else if (msg instanceof HttpContent) { if (tooLongFrameFound) { if (msg instanceof LastHttpContent) { this.currentMessage = null; } // already detect the too long frame so just discard the content return; } assert currentMessage != null; // Merge the received chunk into the content of the current message. HttpContent chunk = (HttpContent) msg; CompositeByteBuf content = (CompositeByteBuf) currentMessage.content(); if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) { tooLongFrameFound = true; // release current message to prevent leaks currentMessage.release(); this.currentMessage = null; throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes."); } // Append the content of the chunk if (chunk.content().isReadable()) { chunk.retain(); content.addComponent(chunk.content()); content.writerIndex(content.writerIndex() + chunk.content().readableBytes()); } final boolean last; if (!chunk.getDecoderResult().isSuccess()) { currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause())); last = true; } else { last = chunk instanceof LastHttpContent; } if (last) { this.currentMessage = null; // Merge trailing headers into the message. if (chunk instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) chunk; currentMessage.setTrailingHeaders(trailer.trailingHeaders()); } else { currentMessage.setTrailingHeaders(new DefaultHttpHeaders()); } // Set the 'Content-Length' header. If one isn't already set. // This is important as HEAD responses will use a 'Content-Length' header which // does not match the actual body, but the number of bytes that would be // transmitted if a GET would have been used. // // See rfc2616 14.13 Content-Length if (!isContentLengthSet(currentMessage)) { currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content.readableBytes())); } // All done out.add(currentMessage); } } else { throw new Error(); } }
From source file:com.cc.nettytest.proxy.decoder.CCLengthFieldBasedFrameDecoder.java
License:Apache License
private void fail(ChannelHandlerContext ctx, long frameLength) { if (frameLength > 0) { ctx.fireExceptionCaught(new TooLongFrameException( "Adjusted frame length exceeds " + maxFrameLength + ": " + frameLength + " - discarded")); } else {/*from ww w . jav a2s .c om*/ ctx.fireExceptionCaught( new TooLongFrameException("Adjusted frame length exceeds " + maxFrameLength + " - discarding")); } }
From source file:com.chat.common.netty.handler.decode.LengthFieldBasedFrameDecoder.java
License:Apache License
private void fail(long frameLength) { if (frameLength > 0) { throw new TooLongFrameException( "Adjusted frame length exceeds " + maxFrameLength + ": " + frameLength + " - discarded"); } else {//from w ww . jav a 2 s . c o m throw new TooLongFrameException("Adjusted frame length exceeds " + maxFrameLength + " - discarding"); } }
From source file:com.facebook.nifty.core.ThriftFrameDecoder.java
License:Apache License
private TTransport tryDecodeFramedMessage(ChannelHandlerContext ctx, ByteBuf buffer) { // Framed messages are prefixed by the size of the frame (which doesn't include the // framing itself). int messageStartReaderIndex = buffer.readerIndex(); // Read the i32 frame contents size int messageContentsLength = buffer.getInt(messageStartReaderIndex); // The full message is larger by the size of the frame size prefix int messageLength = messageContentsLength + MESSAGE_FRAME_SIZE; if (messageContentsLength > maxFrameSize) { ctx.fireExceptionCaught(//from w ww.jav a2 s . c o m new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded")); } int messageContentsOffset = messageStartReaderIndex + MESSAGE_FRAME_SIZE; if (messageLength == 0) { // Zero-sized frame: just ignore it and return nothing buffer.readerIndex(messageContentsOffset); return null; } else if (buffer.readableBytes() < messageLength) { // Full message isn't available yet, return nothing for now return null; } else { // Full message is available, return it ByteBuf messageBuffer = extractFrame(buffer, messageContentsOffset, messageContentsLength); ThriftMessage message = new ThriftMessage(messageBuffer, ThriftTransportType.FRAMED); buffer.readerIndex(messageStartReaderIndex + messageLength); return new TNiftyTransport(ctx.channel(), message); } }
From source file:com.facebook.nifty.core.ThriftFrameDecoder.java
License:Apache License
private TTransport tryDecodeUnframedMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws TException { // Perform a trial decode, skipping through // the fields, to see whether we have an entire message available. int messageLength = 0; int messageStartReaderIndex = buffer.readerIndex(); try {/*from w ww. ja v a 2s .c om*/ TNiftyTransport decodeAttemptTransport = new TNiftyTransport(ctx.channel(), buffer); TProtocol inputProtocol = this.inputProtocolFactory.getProtocol(decodeAttemptTransport); // Skip through the message inputProtocol.readMessageBegin(); TProtocolUtil.skip(inputProtocol, TType.STRUCT); inputProtocol.readMessageEnd(); messageLength = buffer.readerIndex() - messageStartReaderIndex; } catch (IndexOutOfBoundsException e) { // No complete message was decoded: ran out of bytes return null; } finally { if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) { ctx.fireExceptionCaught( new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded")); } buffer.readerIndex(messageStartReaderIndex); } if (messageLength <= 0) { return null; } // We have a full message in the read buffer, slice it off ByteBuf messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength); ThriftMessage message = new ThriftMessage(messageBuffer, ThriftTransportType.UNFRAMED); buffer.readerIndex(messageStartReaderIndex + messageLength); return new TNiftyTransport(ctx.channel(), message); }
From source file:com.growcontrol.common.netty.JsonObjectDecoder.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception { if (this.state == ST_CORRUPTED) { in.skipBytes(in.readableBytes()); return;//from w w w.j av a 2 s . c om } // index of next byte to process. int idx = this.idx; final int wrtIdx = in.writerIndex(); if (wrtIdx > this.maxObjectLength) { // buffer size exceeded maxObjectLength; discarding the complete buffer. in.skipBytes(in.readableBytes()); reset(); throw new TooLongFrameException( "object length exceeds " + this.maxObjectLength + ": " + wrtIdx + " bytes discarded"); } for (/* use current idx */; idx < wrtIdx; idx++) { final byte c = in.getByte(idx); if (this.state == ST_DECODING_NORMAL) { decodeByte(c, in, idx); // All opening braces/brackets have been closed. That's enough to conclude // that the JSON object/array is complete. if (this.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 (this.state == ST_DECODING_ARRAY_STREAM) { decodeByte(c, in, idx); if (!this.insideString && (this.openBraces == 1 && c == ',' || this.openBraces == 0 && c == ']')) { // skip leading spaces. No range check is needed and the loop will terminate // 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); // Discard the array bracket if (this.state == ST_DECODING_ARRAY_STREAM) in.skipBytes(1); // Discard leading spaces in front of a JSON object/array. } else if (Character.isWhitespace(c)) { in.skipBytes(1); } else { this.state = ST_CORRUPTED; throw new CorruptedFrameException( "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in)); } } if (in.readableBytes() == 0) this.idx = 0; else this.idx = idx; }
From source file:com.jamierf.jsonrpc.util.JsonObjectDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (state == ST_CORRUPTED) { in.skipBytes(in.readableBytes()); return;//from www.jav a 2 s.co m } // index of next byte to process. int idx = this.idx; int wrtIdx = in.writerIndex(); if (wrtIdx > maxObjectLength) { // buffer size exceeded maxObjectLength; discarding the complete buffer. in.skipBytes(in.readableBytes()); reset(); throw new TooLongFrameException( "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded"); } for (/* use current idx */; idx < wrtIdx; idx++) { byte c = in.getByte(idx); if (state == ST_DECODING_NORMAL) { decodeByte(c, in, idx); // All opening braces/brackets have been closed. That's enough to conclude // 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 == ']')) { // skip leading spaces. No range check is needed and the loop will terminate // 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.idx = 0; } else { this.idx = idx; } }
From source file:com.mastfrog.acteur.server.HttpObjectAggregator.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { FullHttpMessage currentMessage = this.currentMessage; if (msg instanceof HttpMessage) { tooLongFrameFound = false;//from w ww . j a va 2 s.com assert currentMessage == null; HttpMessage m = (HttpMessage) msg; // Handle the 'Expect: 100-continue' header if necessary. // TODO: Respond with 413 Request Entity Too Large // and discard the traffic or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. if (is100ContinueExpected(m)) { ByteBuf buf = CONTINUE_LINE.duplicate(); buf.retain(); ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); } if (!m.getDecoderResult().isSuccess()) { removeTransferEncodingChunked(m); out.add(toFullMessage(m)); this.currentMessage = null; return; } if (msg instanceof HttpRequest) { HttpRequest header = (HttpRequest) msg; this.currentMessage = currentMessage = new DefaultFullHttpRequest(header.getProtocolVersion(), header.getMethod(), header.getUri(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else if (msg instanceof HttpResponse) { HttpResponse header = (HttpResponse) msg; this.currentMessage = currentMessage = new DefaultFullHttpResponse(header.getProtocolVersion(), header.getStatus(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else { throw new Error(); } currentMessage.headers().set(m.headers()); // A streamed message - initialize the cumulative buffer, and wait for incoming chunks. removeTransferEncodingChunked(currentMessage); } else if (msg instanceof HttpContent) { if (tooLongFrameFound) { if (msg instanceof LastHttpContent) { this.currentMessage = null; } // already detect the too long frame so just discard the content return; } assert currentMessage != null; // Merge the received chunk into the content of the current message. HttpContent chunk = (HttpContent) msg; CompositeByteBuf content = (CompositeByteBuf) currentMessage.content(); if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) { tooLongFrameFound = true; // release current message to prevent leaks currentMessage.release(); this.currentMessage = null; throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes."); } // Append the content of the chunk if (chunk.content().isReadable()) { chunk.retain(); content.addComponent(chunk.content()); content.writerIndex(content.writerIndex() + chunk.content().readableBytes()); } final boolean last; if (!chunk.getDecoderResult().isSuccess()) { currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause())); last = true; } else { last = chunk instanceof LastHttpContent; } if (last) { this.currentMessage = null; // Merge trailing headers into the message. if (chunk instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) chunk; currentMessage.headers().add(trailer.trailingHeaders()); } // Set the 'Content-Length' header. currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content.readableBytes())); // All done out.add(currentMessage); } } else { throw new Error(); } }
From source file:com.mpush.netty.codec.PacketDecoder.java
License:Apache License
private Packet decodeFrame(ByteBuf in) { int readableBytes = in.readableBytes(); int bodyLength = in.readInt(); if (readableBytes < (bodyLength + Packet.HEADER_LEN)) { return null; }/*from w w w. j a va2s . c o m*/ if (bodyLength > maxPacketSize) { throw new TooLongFrameException("packet body length over limit:" + bodyLength); } return decodePacket(new Packet(in.readByte()), in, bodyLength); }