io.netty.handler.codec.CorruptedFrameException Java Examples

The following examples show how to use io.netty.handler.codec.CorruptedFrameException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GSCProtobufVarint32FrameDecoder.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();
    int preIndex = in.readerIndex();
    int length = readRawVarint32(in);
    if (length >= maxMsgLength) {
        logger.error("recv a big msg, host : {}, msg length is : {}", ctx.channel().remoteAddress(),
                length);
        in.clear();
        channel.close();
        return;
    }
    if (preIndex == in.readerIndex()) {
        return;
    }
    if (length < 0) {
        throw new CorruptedFrameException("negative length: " + length);
    }

    if (in.readableBytes() < length) {
        in.resetReaderIndex();
    } else {
        out.add(in.readRetainedSlice(length));
    }
}
 
Example #2
Source File: RntbdObjectMapper.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
static ObjectNode readTree(final ByteBuf in) {

        checkNotNull(in, "in");
        final JsonNode node;

        try (final InputStream istream = new ByteBufInputStream(in)) {
            node = objectMapper.readTree(istream);
        } catch (final IOException error) {
            throw new CorruptedFrameException(error);
        }

        if (node.isObject()) {
            return (ObjectNode)node;
        }

        final String cause = lenientFormat("Expected %s, not %s", JsonNodeType.OBJECT, node.getNodeType());
        throw new CorruptedFrameException(cause);
    }
 
Example #3
Source File: RntbdUUID.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
/**
 * Decode a {@link UUID} as serialized by Microsoft APIs like {@code System.Guid.ToByteArray}
 *
 * @param in a {@link ByteBuf} containing the serialized {@link UUID} to be decoded
 * @return a new {@link UUID}
 */
public static UUID decode(final ByteBuf in) {

    checkNotNull(in, "in");

    if (in.readableBytes() < 2 * Long.BYTES) {
        final String reason = Strings.lenientFormat("invalid frame length: %s", in.readableBytes());
        throw new CorruptedFrameException(reason);
    }

    long mostSignificantBits = in.readUnsignedIntLE() << 32;

    mostSignificantBits |= (0x000000000000FFFFL & in.readShortLE()) << 16;
    mostSignificantBits |= (0x000000000000FFFFL & in.readShortLE());

    long leastSignificantBits = (0x000000000000FFFFL & in.readShortLE()) << (32 + 16);

    for (int shift = 32 + 8; shift >= 0; shift -= 8) {
        leastSignificantBits |= (0x00000000000000FFL & in.readByte()) << shift;
    }

    return new UUID(mostSignificantBits, leastSignificantBits);
}
 
Example #4
Source File: ZWaveFrameDecoder.java    From WZWave with Eclipse Public License 1.0 6 votes vote down vote up
private DataFrame tryCreateDataFrame(ByteBuf in) {
    if (isFullDataFrame(in, in.readerIndex()))
    {
        int frameLength = peekLength(in, in.readerIndex());
        byte calculatedChecksum = calculateChecksum(in, in.readerIndex() + 1, in.readerIndex() + 1 + frameLength);
        byte frameChecksum = peekChecksum(in, in.readerIndex(), frameLength);
        if (calculatedChecksum != frameChecksum)
        {
            in.readBytes(frameLength + 2); // discard frame
            throw new CorruptedFrameException("Invalid frame checksum calc=" + ByteUtil.createString(calculatedChecksum) + " field=" + ByteUtil.createString(frameChecksum));
        }
        ByteBuf frameBuffer = in.readSlice(frameLength + 1);
        in.readByte(); // discard checksum
        return createDataFrame(frameBuffer);
    } else {
        return null;
    }
}
 
Example #5
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testMaxFramePayloadLengthFailed() {
	httpServer = HttpServer.create()
	                       .port(0)
	                       .handle((in, out) -> out.sendWebsocket((i, o) -> o.sendString(Mono.just("12345678901"))))
	                       .wiretap(true)
	                       .bindNow();

	Mono<Void> response = HttpClient.create()
	                                .port(httpServer.port())
	                                .websocket(WebsocketClientSpec.builder().maxFramePayloadLength(10).build())
	                                .handle((in, out) -> in.receive()
	                                                       .asString()
	                                                       .map(srv -> srv))
	                                .log()
	                                .then();

	StepVerifier.create(response)
	            .expectError(CorruptedFrameException.class)
	            .verify(Duration.ofSeconds(30));
}
 
Example #6
Source File: ProtobufVarint32FrameDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
        throws Exception {
    in.markReaderIndex();
    int preIndex = in.readerIndex();
    int length = readRawVarint32(in);
    if (preIndex == in.readerIndex()) {
        return;
    }
    if (length < 0) {
        throw new CorruptedFrameException("negative length: " + length);
    }

    if (in.readableBytes() < length) {
        in.resetReaderIndex();
    } else {
        out.add(in.readRetainedSlice(length));
    }
}
 
Example #7
Source File: MQTTDecoder.java    From vertx-mqtt-broker with Apache License 2.0 6 votes vote down vote up
private void decode(ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();
    if (!Utils.checkHeaderAvailability(in)) {
        in.resetReaderIndex();
        return;
    }
    in.resetReaderIndex();

    byte messageType = Utils.readMessageType(in);

    DemuxDecoder decoder = m_decoderMap.get(messageType);
    if (decoder == null) {
        throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + messageType);
    }
    decoder.decode(in, out);
}
 
Example #8
Source File: Utils.java    From vertx-mqtt-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Encode the value in the format defined in specification as variable length
 * array.
 *
 * @throws IllegalArgumentException if the value is not in the specification bounds
 *  [0..268435455].
 */
static ByteBuf encodeRemainingLength(int value) throws CorruptedFrameException {
    if (value > MAX_LENGTH_LIMIT || value < 0) {
        throw new CorruptedFrameException("Value should in range 0.." + MAX_LENGTH_LIMIT + " found " + value);
    }

    ByteBuf encoded = Unpooled.buffer(4);
    byte digit;
    do {
        digit = (byte) (value % 128);
        value = value / 128;
        // if there are more digits to encode, set the top bit of this digit
        if (value > 0) {
            digit = (byte) (digit | 0x80);
        }
        encoded.writeByte(digit);
    } while (value > 0);
    return encoded;
}
 
Example #9
Source File: JsonObjectDecoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(expected = CorruptedFrameException.class)
public void testNonJsonContent2() {
    EmbeddedChannel ch = new EmbeddedChannel(new JsonObjectDecoder());
    ch.writeInbound(Unpooled.copiedBuffer("  [1,2,3]  ", CharsetUtil.UTF_8));

    ByteBuf res = ch.readInbound();
    assertEquals("[1,2,3]", res.toString(CharsetUtil.UTF_8));
    res.release();

    try {
        ch.writeInbound(Unpooled.copiedBuffer(" a {\"key\" : 10}", CharsetUtil.UTF_8));
    } finally {
        assertFalse(ch.finish());
    }

    fail();
}
 
Example #10
Source File: DatagramDnsResponseDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static DnsResponse newResponse(DatagramPacket packet, ByteBuf buf) {
    final int id = buf.readUnsignedShort();

    final int flags = buf.readUnsignedShort();
    if (flags >> 15 == 0) {
        throw new CorruptedFrameException("not a response");
    }

    final DnsResponse response = new DatagramDnsResponse(
        packet.sender(),
        packet.recipient(),
        id,
        DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)), DnsResponseCode.valueOf((byte) (flags & 0xf)));

    response.setRecursionDesired((flags >> 8 & 1) == 1);
    response.setAuthoritativeAnswer((flags >> 10 & 1) == 1);
    response.setTruncated((flags >> 9 & 1) == 1);
    response.setRecursionAvailable((flags >> 7 & 1) == 1);
    response.setZ(flags >> 4 & 0x7);
    return response;
}
 
Example #11
Source File: RntbdToken.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
@JsonProperty
public Object getValue() {

    final RntbdTokenType.Codec codec = this.header.type().codec();

    if (this.value == null) {
        return codec.defaultValue();
    }

    if (this.value instanceof ByteBuf) {
        final ByteBuf buffer = (ByteBuf) this.value;
        try {
            this.value = codec.defaultValue();
            this.value = codec.read(buffer);
        } catch (final CorruptedFrameException error) {
            String message = lenientFormat("failed to read %s value: %s", this.getName(), error.getMessage());
            throw new CorruptedFrameException(message);
        }
    } else {
        this.value = codec.convert(this.value);
    }

    return this.value;
}
 
Example #12
Source File: DatagramDnsQueryDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static DnsQuery newQuery(DatagramPacket packet, ByteBuf buf) {
    final int id = buf.readUnsignedShort();

    final int flags = buf.readUnsignedShort();
    if (flags >> 15 == 1) {
        throw new CorruptedFrameException("not a query");
    }
    final DnsQuery query =
        new DatagramDnsQuery(
            packet.sender(),
            packet.recipient(),
            id,
            DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)));
    query.setRecursionDesired((flags >> 8 & 1) == 1);
    query.setZ(flags >> 4 & 0x7);
    return query;
}
 
Example #13
Source File: DemuxDecoder.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
private boolean genericDecodeCommonHeader(AbstractMessage message, Integer expectedFlagsOpt, ByteBuf in) {
        //Common decoding part
        if (in.readableBytes() < 2) {
            return false;
        }
        byte h1 = in.readByte();
        byte messageType = (byte) ((h1 & 0x00F0) >> 4);

        byte flags = (byte) (h1 & 0x0F);
        if (expectedFlagsOpt != null) {
            int expectedFlags = expectedFlagsOpt;
            if ((byte) expectedFlags != flags) {
                String hexExpected = Integer.toHexString(expectedFlags);
                String hexReceived = Integer.toHexString(flags);
                String msg = String.format("Received a message with fixed header flags (%s) != expected (%s)", hexReceived, hexExpected);
//                String hex = ConversionUtility.toHexString(in.array(), " ");
//                Container.logger().warn(hex);
                throw new CorruptedFrameException(msg);
            }
        }

        boolean dupFlag = ((byte) ((h1 & 0x0008) >> 3) == 1);
        byte qosLevel = (byte) ((h1 & 0x0006) >> 1);
        boolean retainFlag = ((byte) (h1 & 0x0001) == 1);
        int remainingLength = Utils.decodeRemainingLenght(in);
        if (remainingLength == -1) {
            return false;
        }

        message.setMessageType(messageType);
        message.setDupFlag(dupFlag);
        message.setQos(AbstractMessage.QOSType.values()[qosLevel]);
        message.setRetainFlag(retainFlag);
        message.setRemainingLength(remainingLength);
        return true;
    }
 
Example #14
Source File: RntbdResponseHeaders.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Override
public String toString() {
    final ObjectWriter writer = RntbdObjectMapper.writer();
    try {
        return writer.writeValueAsString(this);
    } catch (final JsonProcessingException error) {
        throw new CorruptedFrameException(error);
    }
}
 
Example #15
Source File: VotifierProtocol2HandshakeHandler.java    From NuVotifier with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, String s) {
    String[] handshakeContents = s.split(" ");
    if (handshakeContents.length != 3) {
        throw new CorruptedFrameException("Handshake is not valid.");
    }

    VoteRequest request = new VoteRequest(handshakeContents[2], toSend);
    if (nuVotifier.isDebug()) {
        nuVotifier.getPluginLogger().info("Sent request: " + request.toString());
    }
    ctx.writeAndFlush(request);
    ctx.pipeline().addLast(new VotifierProtocol2ResponseHandler(responseHandler));
    ctx.pipeline().remove(this);
}
 
Example #16
Source File: RiemannFrameDecoder.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
    throws Exception {
    if (in.readableBytes() < 4) {
        return;
    }

    final long length = in.getUnsignedInt(0);

    if (length > MAX_SIZE) {
        throw new CorruptedFrameException(
            String.format("frame size (%s) larger than max (%d)", length, MAX_SIZE));
    }

    final int intLength = (int) length;

    if (in.readableBytes() < (4 + length)) {
        return;
    }

    in.skipBytes(4);
    final ByteBuf frame = in.readBytes(intLength);

    try {
        out.add(serializer.parse0(frame));
    } finally {
        frame.release();
    }
}
 
Example #17
Source File: WireCommands.java    From pravega with Apache License 2.0 5 votes vote down vote up
public static WireCommand readFrom(DataInput in, int length) throws IOException {
    int skipped = 0;
    while (skipped < length) {
        int skipBytes = in.skipBytes(length - skipped);
        if (skipBytes < 0) {
            throw new CorruptedFrameException("Not enough bytes in buffer. Was attempting to read: " + length);
        }
        skipped += skipBytes;
    }
    return new Padding(length);
}
 
Example #18
Source File: MessageDecoder.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static int readRawVarint32(ByteBufInputStream is) throws IOException {
  byte tmp = is.readByte();
  if (tmp >= 0) {
    return tmp;
  }
  int result = tmp & 0x7f;
  if ((tmp = is.readByte()) >= 0) {
    result |= tmp << 7;
  } else {
    result |= (tmp & 0x7f) << 7;
    if ((tmp = is.readByte()) >= 0) {
      result |= tmp << 14;
    } else {
      result |= (tmp & 0x7f) << 14;
      if ((tmp = is.readByte()) >= 0) {
        result |= tmp << 21;
      } else {
        result |= (tmp & 0x7f) << 21;
        result |= (tmp = is.readByte()) << 28;
        if (tmp < 0) {
          // Discard upper 32 bits.
          for (int i = 0; i < 5; i++) {
            if (is.readByte() >= 0) {
              return result;
            }
          }
          throw new CorruptedFrameException("Encountered a malformed varint.");
        }
      }
    }
  }
  return result;
}
 
Example #19
Source File: Misc.java    From Almost-Famous with MIT License 5 votes vote down vote up
public static int toInt(ByteBuf in) {
    if (in.readableBytes() < 4) {
        throw new CorruptedFrameException("to int.");
    }
    return ((in.readByte() & 0xff) << 24) | ((in.readByte() & 0xff) << 16) | ((in.readByte() & 0xff) << 8)
            | ((in.readByte() & 0xff) << 0);
}
 
Example #20
Source File: RntbdFramer.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
static boolean canDecodePayload(final ByteBuf in, final int start) {

        checkNotNull(in, "in");

        final int readerIndex = in.readerIndex();

        if (start < readerIndex) {
            throw new IllegalArgumentException("start < in.readerIndex()");
        }

        final int offset = start - readerIndex;

        if (in.readableBytes() - offset < Integer.BYTES) {
            return false;
        }

        final long length = in.getUnsignedIntLE(start);

        if (length > Integer.MAX_VALUE) {
            final String reason = Strings.lenientFormat("Payload frame length exceeds Integer.MAX_VALUE, %s: %s",
                Integer.MAX_VALUE, length
            );
            throw new CorruptedFrameException(reason);
        }

        return offset + Integer.BYTES + length <= in.readableBytes();
    }
 
Example #21
Source File: RntbdContextRequest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Override
public String toString() {
    final ObjectWriter writer = RntbdObjectMapper.writer();
    try {
        return writer.writeValueAsString(this);
    } catch (final JsonProcessingException error) {
        throw new CorruptedFrameException(error);
    }
}
 
Example #22
Source File: BigIntegerDecoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    // Wait until the length prefix is available.
    if (in.readableBytes() < 5) {
        return;
    }

    in.markReaderIndex();

    // Check the magic number.
    int magicNumber = in.readUnsignedByte();
    if (magicNumber != 'F') {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Invalid magic number: " + magicNumber);
    }

    // Wait until the whole data is available.
    int dataLength = in.readInt();
    if (in.readableBytes() < dataLength) {
        in.resetReaderIndex();
        return;
    }

    // Convert the received data into a new BigInteger.
    byte[] decoded = new byte[dataLength];
    in.readBytes(decoded);

    out.add(new BigInteger(decoded));
}
 
Example #23
Source File: Utf8Validator.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(byte b) throws Exception {
    byte type = TYPES[b & 0xFF];

    codep = state != UTF8_ACCEPT ? b & 0x3f | codep << 6 : 0xff >> type & b;

    state = STATES[state + type];

    if (state == UTF8_REJECT) {
        checking = false;
        throw new CorruptedFrameException("bytes are not UTF-8");
    }
    return true;
}
 
Example #24
Source File: WebSocket08FrameDecoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private void protocolViolation(ChannelHandlerContext ctx, CorruptedFrameException ex) {
    checkpoint(State.CORRUPT);
    if (ctx.channel().isActive()) {
        Object closeMessage;
        if (receivedClosingHandshake) {
            closeMessage = Unpooled.EMPTY_BUFFER;
        } else {
            closeMessage = new CloseWebSocketFrame(1002, null);
        }
        ctx.writeAndFlush(closeMessage).addListener(ChannelFutureListener.CLOSE);
    }
    throw ex;
}
 
Example #25
Source File: WebSocket08FrameDecoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private void checkUTF8String(ChannelHandlerContext ctx, ByteBuf buffer) {
    try {
        if (utf8Validator == null) {
            utf8Validator = new Utf8Validator();
        }
        utf8Validator.check(buffer);
    } catch (CorruptedFrameException ex) {
        protocolViolation(ctx, ex);
    }
}
 
Example #26
Source File: WebSocket08FrameDecoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/** */
protected void checkCloseFrameBody(
        ChannelHandlerContext ctx, ByteBuf buffer) {
    if (buffer == null || !buffer.isReadable()) {
        return;
    }
    if (buffer.readableBytes() == 1) {
        protocolViolation(ctx, "Invalid close frame body");
    }

    // Save reader index
    int idx = buffer.readerIndex();
    buffer.readerIndex(0);

    // Must have 2 byte integer within the valid range
    int statusCode = buffer.readShort();
    if (statusCode >= 0 && statusCode <= 999 || statusCode >= 1004 && statusCode <= 1006
            || statusCode >= 1012 && statusCode <= 2999) {
        protocolViolation(ctx, "Invalid close frame getStatus code: " + statusCode);
    }

    // May have UTF-8 message
    if (buffer.isReadable()) {
        try {
            new Utf8Validator().check(buffer);
        } catch (CorruptedFrameException ex) {
            protocolViolation(ctx, ex);
        }
    }

    // Restore reader index
    buffer.readerIndex(idx);
}
 
Example #27
Source File: VarIntFrameDecoder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf input, List<Object> list)  {
	if (packetLength == -1) {
		input.markReaderIndex();
		int tmpPacketLength = 0;
		for (int i = 0; i < 3; ++i) {
			if (!input.isReadable()) {
				input.resetReaderIndex();
				return;
			}
			int part = input.readByte();
			tmpPacketLength |= (part & 0x7F) << (i * 7);
			if (part >= 0) {
				packetLength = tmpPacketLength;
				if (packetLength == 0) {
					packetLength = -1;
				}
				return;
			}
		}
		throw new CorruptedFrameException("Packet length varint length is more than 21 bits");
	}
       if (input.readableBytes() < packetLength) {
           return;
       }
       list.add(input.readBytes(packetLength));
       packetLength = -1;
}
 
Example #28
Source File: MinecraftDecoder.java    From Velocity with MIT License 5 votes vote down vote up
private Exception handleDecodeFailure(Exception cause, MinecraftPacket packet, int packetId) {
  if (DEBUG) {
    return new CorruptedFrameException(
        "Error decoding " + packet.getClass() + " " + getExtraConnectionDetail(packetId), cause);
  } else {
    return DECODE_FAILED;
  }
}
 
Example #29
Source File: MinecraftDecoder.java    From Velocity with MIT License 5 votes vote down vote up
private Exception handleNotReadEnough(MinecraftPacket packet, int packetId) {
  if (DEBUG) {
    return new CorruptedFrameException("Did not read full packet for " + packet.getClass() + " "
        + getExtraConnectionDetail(packetId));
  } else {
    return DECODE_FAILED;
  }
}
 
Example #30
Source File: MinecraftVarintFrameDecoder.java    From Velocity with MIT License 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  if (!in.isReadable()) {
    return;
  }

  int origReaderIndex = in.readerIndex();
  for (int i = 0; i < 3; i++) {
    if (!in.isReadable()) {
      in.readerIndex(origReaderIndex);
      return;
    }

    byte read = in.readByte();
    if (read >= 0) {
      // Make sure reader index of length buffer is returned to the beginning
      in.readerIndex(origReaderIndex);
      int packetLength = ProtocolUtils.readVarInt(in);
      if (packetLength == 0) {
        return;
      }

      if (in.readableBytes() < packetLength) {
        in.readerIndex(origReaderIndex);
        return;
      }

      out.add(in.readRetainedSlice(packetLength));
      return;
    }
  }

  throw new CorruptedFrameException("VarInt too big");
}