Java Code Examples for io.netty.buffer.ByteBuf#getUnsignedByte()

The following examples show how to use io.netty.buffer.ByteBuf#getUnsignedByte() . 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: XROIpv4PrefixSubobjectParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public SubobjectContainer parseSubobject(final ByteBuf buffer, final boolean mandatory)
        throws RSVPParsingException {
    checkArgument(buffer != null && buffer.isReadable(), "Array of bytes is mandatory. Can't be null or empty.");
    final SubobjectContainerBuilder builder = new SubobjectContainerBuilder();
    builder.setMandatory(mandatory);
    if (buffer.readableBytes() != CONTENT4_LENGTH) {
        throw new RSVPParsingException("Wrong length of array of bytes. Passed: " + buffer.readableBytes() + ";");
    }
    final int length = buffer.getUnsignedByte(PREFIX4_F_OFFSET);
    final IpPrefixBuilder prefix = new IpPrefixBuilder().setIpPrefix(new IpPrefix(
        Ipv4Util.prefixForBytes(ByteArray.readBytes(buffer, Ipv4Util.IP4_LENGTH), length)));
    builder.setSubobjectType(new IpPrefixCaseBuilder().setIpPrefix(prefix.build()).build());
    buffer.skipBytes(PREFIX_F_LENGTH);
    builder.setAttribute(ExcludeRouteSubobjects.Attribute.forValue(buffer.readUnsignedByte()));
    return builder.build();
}
 
Example 2
Source File: XROIpv4PrefixSubobjectParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Subobject parseSubobject(final ByteBuf buffer, final boolean mandatory) throws PCEPDeserializerException {
    checkArgument(buffer != null && buffer.isReadable(), "Array of bytes is mandatory. Cannot be null or empty.");
    if (buffer.readableBytes() != CONTENT4_LENGTH) {
        throw new PCEPDeserializerException("Wrong length of array of bytes. Passed: " + buffer.readableBytes()
            + ";");
    }
    final int length = buffer.getUnsignedByte(PREFIX4_F_OFFSET);
    final IpPrefixBuilder prefix = new IpPrefixBuilder()
            .setIpPrefix(new IpPrefix(Ipv4Util.prefixForBytes(ByteArray.readBytes(buffer, Ipv4Util.IP4_LENGTH),
                length)));
    buffer.skipBytes(PREFIX_F_LENGTH);
    return new SubobjectBuilder()
            .setMandatory(mandatory)
            .setSubobjectType(new IpPrefixCaseBuilder().setIpPrefix(prefix.build()).build())
            .setAttribute(Attribute.forValue(buffer.readUnsignedByte()))
            .build();
}
 
Example 3
Source File: ServerMessageDecoder.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Nullable
private static ServerMessage decodePreparedMetadata(ByteBuf buf, ConnectionContext context, PreparedMetadataDecodeContext decodeContext) {
    short header = buf.getUnsignedByte(buf.readerIndex());

    if (header == ERROR) {
        // 0xFF is not header of var integer,
        // not header of text result null (0xFB) and
        // not header of column metadata (0x03 + "def")
        return ErrorMessage.decode(buf);
    }

    if (decodeContext.isInMetadata()) {
        return decodeInMetadata(buf, header, context, decodeContext);
    }

    throw new R2dbcNonTransientResourceException(String.format("Unknown message header 0x%x and readable bytes is %d on prepared metadata phase", header, buf.readableBytes()));
}
 
Example 4
Source File: HermesLengthFieldBasedFrameDecoder.java    From hermes with Apache License 2.0 6 votes vote down vote up
/**
 * Decodes the specified region of the buffer into an unadjusted frame length. The default implementation is capable of decoding
 * the specified region into an unsigned 8/16/24/32/64 bit integer. Override this method to decode the length field encoded
 * differently. Note that this method must not modify the state of the specified buffer (e.g. {@code readerIndex},
 * {@code writerIndex}, and the content of the buffer.)
 *
 * @throws DecoderException
 *            if failed to decode the specified region
 */
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
	buf = buf.order(order);
	long frameLength;
	switch (length) {
	case 1:
		frameLength = buf.getUnsignedByte(offset);
		break;
	case 2:
		frameLength = buf.getUnsignedShort(offset);
		break;
	case 3:
		frameLength = buf.getUnsignedMedium(offset);
		break;
	case 4:
		frameLength = buf.getUnsignedInt(offset);
		break;
	case 8:
		frameLength = buf.getLong(offset);
		break;
	default:
		throw new DecoderException("unsupported lengthFieldLength: " + lengthFieldLength
		      + " (expected: 1, 2, 3, 4, or 8)");
	}
	return frameLength;
}
 
Example 5
Source File: VarIntUtils.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
/**
 * @param buf a readable buffer for check it has next a var integer or not.
 * @return a negative integer means {@code buf} has not a var integer,
 * return 0 means {@code buf} looks like has only a var integer which buffer has no other data,
 * return a positive integer means how much buffer size after read a var integer.
 */
public static int checkNextVarInt(ByteBuf buf) {
    int byteSize = requireNonNull(buf, "buf must not be null").readableBytes();

    if (byteSize <= 0) {
        return -1;
    }

    short firstByte = buf.getUnsignedByte(buf.readerIndex());

    if (firstByte < VAR_INT_2_BYTE_CODE) {
        return byteSize - Byte.BYTES;
    } else if (firstByte == VAR_INT_2_BYTE_CODE) {
        return byteSize - (Byte.BYTES + Short.BYTES);
    } else if (firstByte == VAR_INT_3_BYTE_CODE) {
        return byteSize - (Byte.BYTES + MEDIUM_BYTES);
    } else if (firstByte == VAR_INT_8_BYTE_CODE) {
        return byteSize - (Byte.BYTES + Long.BYTES);
    } else {
        return -1;
    }
}
 
Example 6
Source File: Stateful07LspObjectParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Lsp parseObject(final ObjectHeader header, final ByteBuf bytes) throws PCEPDeserializerException {
    checkArgument(bytes != null && bytes.isReadable(), "Array of bytes is mandatory. Can't be null or empty.");
    final LspBuilder builder = new LspBuilder();
    builder.setIgnore(header.isIgnore());
    builder.setProcessingRule(header.isProcessingRule());
    final int[] plspIdRaw
        = new int[] { bytes.readUnsignedByte(), bytes.readUnsignedByte(), bytes.getUnsignedByte(2), };
    builder.setPlspId(new PlspId(Uint32.valueOf(plspIdRaw[0] << FLAGS_SIZE | plspIdRaw[1] << FOUR_BITS_SHIFT
        | plspIdRaw[2] >> FOUR_BITS_SHIFT)));
    parseFlags(builder, bytes);
    final TlvsBuilder b = new TlvsBuilder();
    parseTlvs(b, bytes.slice());
    builder.setTlvs(b.build());
    return builder.build();
}
 
Example 7
Source File: ServerMessageDecoder.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Nullable
private static ServerMessage decodePreparedMetadata(ByteBuf buf, ConnectionContext context, PreparedMetadataDecodeContext decodeContext) {
    short header = buf.getUnsignedByte(buf.readerIndex());

    if (header == ERROR) {
        // 0xFF is not header of var integer,
        // not header of text result null (0xFB) and
        // not header of column metadata (0x03 + "def")
        return ErrorMessage.decode(buf);
    }

    if (decodeContext.isInMetadata()) {
        return decodeInMetadata(buf, header, context, decodeContext);
    }

    throw new R2dbcNonTransientResourceException(String.format("Unknown message header 0x%x and readable bytes is %d on prepared metadata phase", header, buf.readableBytes()));
}
 
Example 8
Source File: PacketFramer.java    From socketio with Apache License 2.0 5 votes vote down vote up
private static int getUtf8ByteCountByCharCount(final ByteBuf buffer, final int startIndex, final int charCount) {
  int bytesCount = 0;
  for (int charIndex = 0; charIndex < charCount; charIndex++) {
    // Define next char first byte
    int charFirstByteIndex = startIndex + bytesCount;
    short charFirstByte = buffer.getUnsignedByte(charFirstByteIndex);

    // Scan first byte of UTF-8 character according to:
    // http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
    if ((charFirstByte >= 0x20) && (charFirstByte <= 0x7F)) {
      // characters U-00000000 - U-0000007F (same as ASCII)
      bytesCount++;
    } else if ((charFirstByte & 0xE0) == 0xC0) {
      // characters U-00000080 - U-000007FF, mask 110XXXXX
      bytesCount += 2;
    } else if ((charFirstByte & 0xF0) == 0xE0) {
      // characters U-00000800 - U-0000FFFF, mask 1110XXXX
      bytesCount += 3;
    } else if ((charFirstByte & 0xF8) == 0xF0) {
      // characters U-00010000 - U-001FFFFF, mask 11110XXX
      bytesCount += 4;
    } else if ((charFirstByte & 0xFC) == 0xF8) {
      // characters U-00200000 - U-03FFFFFF, mask 111110XX
      bytesCount += 5;
    } else if ((charFirstByte & 0xFE) == 0xFC) {
      // characters U-04000000 - U-7FFFFFFF, mask 1111110X
      bytesCount += 6;
    } else {
      bytesCount++;
    }
  }
  return bytesCount;
}
 
Example 9
Source File: MuCryptUtils.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
static int GetHeaderSize(ByteBuf buff)
{
	switch(buff.getUnsignedByte(0))
	{
		case 0xC1:
		case 0xC3:
			return 2;
		case 0xC2:
		case 0xC4:
			return 3;
	}
	return -1;
}
 
Example 10
Source File: NonSslHandler.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {

    //Needs minimum 5 bytes to be able to tell what it is.
    if (in.readableBytes() < 11) {
        return;
    }

    //Check for SSL bytes
    final boolean encrypted = SslHandler.isEncrypted(in);

    //With MQTT5 it is possible to craft a valid CONNECT packet, that matches an SSLv2 packet
    final boolean isConnectPacket = in.getUnsignedByte(0) == 16;
    final boolean isMqttPacket = in.getUnsignedByte(7) == 'M' &&
            in.getUnsignedByte(8) == 'Q' &&
            in.getUnsignedByte(9) == 'T' &&
            in.getUnsignedByte(10) == 'T';

    if (encrypted && !(isConnectPacket && isMqttPacket)) {
        log.debug("SSL connection on non-SSL listener, dropping connection.");
        in.clear();
        eventLog.clientWasDisconnected(ctx.channel(), "SSL connection to non-SSL listener");
        ctx.close();
        return;
    }

    ctx.pipeline().remove(this);
}
 
Example 11
Source File: SimpleQueryCommandCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleInitPacket(ByteBuf payload) {
  // may receive ERR_Packet, OK_Packet, LOCAL INFILE Request, Text Resultset
  int firstByte = payload.getUnsignedByte(payload.readerIndex());
  if (firstByte == OK_PACKET_HEADER) {
    OkPacket okPacket = decodeOkPacketPayload(payload);
    handleSingleResultsetDecodingCompleted(okPacket.serverStatusFlags(), okPacket.affectedRows(), okPacket.lastInsertId());
  } else if (firstByte == ERROR_PACKET_HEADER) {
    handleErrorPacketPayload(payload);
  } else if (firstByte == 0xFB) {
    handleLocalInfile(payload);
  } else {
    handleResultsetColumnCountPacketBody(payload);
  }
}
 
Example 12
Source File: WritePacket.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
public boolean isEncryptable(ByteBuf buff)
{
	switch (buff.getUnsignedByte(0)) {
		case 0xC3:
		case 0xC4:
			return true;
	}
	
	return false;
}
 
Example 13
Source File: ServerMessageDecoder.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static ServerMessage decodeCommandMessage(ByteBuf buf, ConnectionContext context) {
    short header = buf.getUnsignedByte(buf.readerIndex());
    switch (header) {
        case ERROR:
            return ErrorMessage.decode(buf);
        case OK:
            if (OkMessage.isValidSize(buf.readableBytes())) {
                return OkMessage.decode(buf, context);
            }

            break;
        case EOF:
            int byteSize = buf.readableBytes();

            // Maybe OK, maybe column count (unsupported EOF on command phase)
            if (OkMessage.isValidSize(byteSize)) {
                // MySQL has hard limit of 4096 columns per-table,
                // so if readable bytes upper than 7, it means if it is column count,
                // column count is already upper than (1 << 24) - 1 = 16777215, it is impossible.
                // So it must be OK message, not be column count.
                return OkMessage.decode(buf, context);
            } else if (EofMessage.isValidSize(byteSize)) {
                return EofMessage.decode(buf);
            }
    }

    if (VarIntUtils.checkNextVarInt(buf) == 0) {
        // EOF message must be 5-bytes, it will never be looks like a var integer.
        // It looks like has only a var integer, should be column count.
        return ColumnCountMessage.decode(buf);
    }

    throw new R2dbcNonTransientResourceException(String.format("Unknown message header 0x%x and readable bytes is %d on command phase", header, buf.readableBytes()));
}
 
Example 14
Source File: ServerMessageDecoder.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static ServerMessage decodeFetch(List<ByteBuf> buffers, ConnectionContext context) {
    ByteBuf firstBuf = buffers.get(0);
    short header = firstBuf.getUnsignedByte(firstBuf.readerIndex());
    ErrorMessage error = decodeCheckError(buffers, header);

    if (error != null) {
        return error;
    }

    return decodeRow(buffers, firstBuf, header, context, "fetch");
}
 
Example 15
Source File: WritePacket.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
public void markLength(ByteBuf buff) {
	int lenght = buff.writerIndex();
	switch (buff.getUnsignedByte(0)) {
		case 0xC1:
		case 0xC3:
			buff.setByte(1, lenght);
			break;
		case 0xC2:
		case 0xC4:
			buff.setByte(1, lenght >> 8);
			buff.setByte(2, lenght & 0xFF);
			break;
	}
}
 
Example 16
Source File: Packet.java    From riiablo with Apache License 2.0 4 votes vote down vote up
public static int getNumFragments(ByteBuf bb) {
  return bb.getUnsignedByte(NUMFRAG_OFFSET);
}
 
Example 17
Source File: Packet.java    From riiablo with Apache License 2.0 4 votes vote down vote up
public static int getChunkId(ByteBuf bb) {
  return bb.getUnsignedByte(CHUNKID_OFFSET);
}
 
Example 18
Source File: LispLcafAddress.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public LispLcafAddress readFrom(ByteBuf byteBuf)
        throws LispParseError, LispReaderException {

    int index = byteBuf.readerIndex();

    // LCAF type -> 8 bits
    byte lcafType = (byte) byteBuf.getUnsignedByte(index + LCAF_TYPE_FIELD_INDEX);

    if (lcafType == APPLICATION_DATA.getLispCode()) {
        return new LispAppDataLcafAddress.AppDataLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == NAT.getLispCode()) {
        return new LispNatLcafAddress.NatLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == LIST.getLispCode()) {
        return new LispListLcafAddress.ListLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == SEGMENT.getLispCode()) {
        return new LispSegmentLcafAddress.SegmentLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == GEO_COORDINATE.getLispCode()) {
        return new LispGeoCoordinateLcafAddress.GeoCoordinateLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == NONCE.getLispCode()) {
        return new LispNonceLcafAddress.NonceLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == MULTICAST.getLispCode()) {
        return new LispMulticastLcafAddress.MulticastLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == SOURCE_DEST.getLispCode()) {
        return new LispSourceDestLcafAddress.SourceDestLcafAddressReader().readFrom(byteBuf);
    }

    if (lcafType == TRAFFIC_ENGINEERING.getLispCode()) {
        return new LispTeLcafAddress.TeLcafAddressReader().readFrom(byteBuf);
    }

    log.warn("Unsupported LCAF type, please specify a correct LCAF type");

    return null;
}
 
Example 19
Source File: MuCryptUtils.java    From vethrfolnir-mu with GNU General Public License v3.0 4 votes vote down vote up
public static final short[] getAsUByteArray(ByteBuf buff, short[] uByteArray) {
	for (int i = 0; i < uByteArray.length; i++) {
		uByteArray[i] = buff.getUnsignedByte(i);
	}
	return uByteArray;
}
 
Example 20
Source File: APDUDecoder.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void decode ( final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out ) throws Exception
{
    if ( logger.isTraceEnabled () )
    {
        logger.trace ( "decode - bytes: {}", ByteBufUtil.hexDump ( in ) );
    }

    if ( in.readableBytes () < Constants.APCI_MIN_LENGTH )
    {
        return;
    }

    final byte start = in.getByte ( in.readerIndex () + 0 );
    if ( start != Constants.START_BYTE )
    {
        throw new DecoderException ( String.format ( "ACPI must start with 0x%02x but did with 0x%02x", Constants.START_BYTE, start ) );
    }

    final short len = in.getUnsignedByte ( in.readerIndex () + 1 );

    if ( len > Constants.APCI_MAX_DATA_LENGTH )
    {
        throw new DecoderException ( String.format ( "APCI has a maximum length of %s bytes, but we received %s", Constants.APCI_MAX_DATA_LENGTH, len ) );
    }

    if ( in.readableBytes () < len + 2 )
    {
        return;
    }

    // we have the full InformationTransfer

    // skip start & len
    in.skipBytes ( 2 );

    // read control fields
    final ByteBuf controlFields = in.readSlice ( 4 );

    final ByteBuf data;
    if ( len > 4 )
    {
        data = Unpooled.copiedBuffer ( in.readSlice ( len - 4 ) ).order ( ByteOrder.LITTLE_ENDIAN );
    }
    else
    {
        data = null;
    }

    // now add the PDU

    out.add ( decode ( controlFields, data ) );
}