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

The following examples show how to use io.netty.buffer.ByteBuf#readUnsignedShort() . 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: OpaqueUtil.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
public static Opaque parseOpaque(final ByteBuf buffer) {
    final Uint8 type = ByteBufUtils.readUint8(buffer);
    final OpaqueValueBuilder builder = new OpaqueValueBuilder();
    switch (type.toJava()) {
        case GENERIC_LSP_IDENTIFIER:
            builder.setOpaque(buildOpaqueValue(buffer));
            break;
        case EXTENDED_TYPE:
            buildExtended(builder, buffer);
            break;
        default:
            final int length = buffer.readUnsignedShort();
            buffer.skipBytes(length);
            LOG.debug("Skipping parsing of Opaque Value {}", buffer);
            return null;
    }
    return builder.setOpaqueType(type).build();
}
 
Example 2
Source File: GeoWaveMetadataCodec.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public Object decode(final ByteBuf buf, final State state) throws IOException {
  final byte[] primaryId = new byte[buf.readUnsignedByte()];
  final byte[] secondaryId = new byte[buf.readUnsignedByte()];
  final byte[] visibility;
  if (visibilityEnabled) {
    visibility = new byte[buf.readUnsignedByte()];
  } else {
    visibility = new byte[0];
  }
  final byte[] value = new byte[buf.readUnsignedShort()];
  buf.readBytes(primaryId);
  buf.readBytes(secondaryId);
  if (visibilityEnabled) {
    buf.readBytes(visibility);
  }
  buf.readBytes(value);
  return new GeoWaveMetadata(primaryId, secondaryId, visibility, value);
}
 
Example 3
Source File: GetPlayersResultDecoder.java    From JLilyPad with GNU General Public License v3.0 6 votes vote down vote up
public GetPlayersResult decode(StatusCode statusCode, ByteBuf buffer) {
	if(statusCode == StatusCode.SUCCESS) {
		boolean hasList = buffer.readBoolean();
		int currentPlayers = buffer.readUnsignedShort();
		int maximumPlayers = buffer.readUnsignedShort();
		Set<String> players = new HashSet<String>();
		if(hasList) {
			for(int i = 0; i < currentPlayers; i++) {
				players.add(BufferUtils.readString(buffer));
			}
		}
		return new GetPlayersResult(currentPlayers, maximumPlayers, players);
	} else {
		return new GetPlayersResult(statusCode);
	}
}
 
Example 4
Source File: TeLspAttributesParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
static LinkStateAttribute parseTeLspAttributes(final RSVPTeObjectRegistry registry, final ByteBuf attributes)
        throws BGPParsingException {

    final TeLspAttributesBuilder builder = new TeLspAttributesBuilder();
    LOG.trace("Initiated parsing TE LSP Objects.");
    while (attributes.isReadable()) {
        final int length = attributes.readUnsignedShort();
        final int classNum = attributes.readUnsignedByte();
        final int cType = attributes.readUnsignedByte();
        final ByteBuf value = attributes.readSlice(length);
        try {
            addObject(builder, registry.parseRSPVTe(classNum, cType, value));
        } catch (final RSVPParsingException e) {
            LOG.debug("Parsering TE LSP Object error. class number: {} cType: {} value: {}", classNum, cType, value,
                e);
            throw new BGPParsingException(e.getMessage(), e);
        }
    }
    LOG.trace("Finished parsing TE LSP Objects.");
    return new TeLspAttributesCaseBuilder().setTeLspAttributes(builder.build()).build();
}
 
Example 5
Source File: DatagramDnsResponseDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
    final ByteBuf buf = packet.content();

    final DnsResponse response = newResponse(packet, buf);
    boolean success = false;
    try {
        final int questionCount = buf.readUnsignedShort();
        final int answerCount = buf.readUnsignedShort();
        final int authorityRecordCount = buf.readUnsignedShort();
        final int additionalRecordCount = buf.readUnsignedShort();

        decodeQuestions(response, buf, questionCount);
        decodeRecords(response, DnsSection.ANSWER, buf, answerCount);
        decodeRecords(response, DnsSection.AUTHORITY, buf, authorityRecordCount);
        decodeRecords(response, DnsSection.ADDITIONAL, buf, additionalRecordCount);

        out.add(response);
        success = true;
    } finally {
        if (!success) {
            response.release();
        }
    }
}
 
Example 6
Source File: RSCProtocolDecoder.java    From Game with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
	if (buffer.readableBytes() > 2) {
		buffer.markReaderIndex();
		int length = buffer.readUnsignedShort();
		if (buffer.readableBytes() >= length && length > 0) {
			int opcode = (buffer.readByte()) & 0xFF;
			length -= 1;
			ByteBuf data = Unpooled.buffer(length);
			buffer.readBytes(data, length);
			Packet packet = new Packet(opcode, data);
			out.add(packet);
		} else {
			buffer.resetReaderIndex();
		}
	}
}
 
Example 7
Source File: FtdcProtocol.java    From ftdc with Apache License 2.0 6 votes vote down vote up
public Ftdc(ByteBuf body) {
	this.version = body.readByte();
	this.type = body.readByte();
	this.unencodeLength = body.readByte();
	this.chain = body.readByte();
	this.sequenceType = body.readShort();
	this.sequence = body.readInt();
	this.currentSequence = body.readInt();
	this.numData = body.readShort();
	this.ftdcLen = body.readUnsignedShort();
	this.reqId = body.readUnsignedInt();
	//没有数据的情况是不存在tid的
	if(ftdcLen != 0) {
		this.tid = body.readUnsignedInt();
		int actualLen = this.ftdcLen - 4;
		if(body.readableBytes() < actualLen) {
			throw new IllegalArgumentException("bad body length");
		}
		ftdcBody = body.retainedSlice(body.readerIndex(), actualLen);
	}
	
}
 
Example 8
Source File: RequiredAttributesObjectParser.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected RsvpTeObject localParseObject(final ByteBuf byteBuf) throws RSVPParsingException {
    final LspRequiredAttributesObjectBuilder builder = new LspRequiredAttributesObjectBuilder();

    final List<SubobjectContainer> subObjectList = new ArrayList<>();
    while (byteBuf.isReadable()) {
        final int type = byteBuf.readUnsignedShort();
        final int length = byteBuf.readUnsignedShort();
        final ByteBuf value = byteBuf.readSlice(length);
        final SubobjectContainerBuilder subObj = new SubobjectContainerBuilder();
        if (type == AttributesObjectParser.FLAG_TLV_TYPE) {
            subObj.setLspSubobject(new FlagsTlvBuilder().setFlagContainer(AttributesObjectParser.parseFlag(value)
            ).build());
        } else {
            LOG.warn("Lsp Attributes Subobject type {} not supported", type);
        }
        subObjectList.add(subObj.build());
    }

    return builder.setLspAttributesObject(new LspAttributesObjectBuilder().setSubobjectContainer(subObjectList)
        .build()).build();
}
 
Example 9
Source File: GeoWaveMetadataWithTimestampCodec.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public Object decode(final ByteBuf buf, final State state) throws IOException {
  final byte[] primaryId = new byte[buf.readUnsignedByte()];
  final byte[] secondaryId = new byte[buf.readUnsignedByte()];
  final byte[] visibility;
  if (visibilityEnabled) {
    visibility = new byte[buf.readUnsignedByte()];
  } else {
    visibility = new byte[0];
  }
  final byte[] value = new byte[buf.readUnsignedShort()];
  buf.readBytes(primaryId);
  buf.readBytes(secondaryId);
  buf.readBytes(visibility);
  buf.readBytes(value);
  return new GeoWaveTimestampMetadata(
      primaryId,
      secondaryId,
      visibility,
      value,
      buf.readLong());
}
 
Example 10
Source File: SendUnitData.java    From ethernet-ip with Apache License 2.0 5 votes vote down vote up
public static SendUnitData decode(ByteBuf buffer) {
    return new SendUnitData(
        buffer.readUnsignedInt(),
        buffer.readUnsignedShort(),
        CpfPacket.decode(buffer)
    );
}
 
Example 11
Source File: Socks5CommandRequestDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    try {
        switch (state()) {
        case INIT: {
            final byte version = in.readByte();
            if (version != SocksVersion.SOCKS5.byteValue()) {
                throw new DecoderException(
                        "unsupported version: " + version + " (expected: " + SocksVersion.SOCKS5.byteValue() + ')');
            }

            final Socks5CommandType type = Socks5CommandType.valueOf(in.readByte());
            in.skipBytes(1); // RSV
            final Socks5AddressType dstAddrType = Socks5AddressType.valueOf(in.readByte());
            final String dstAddr = addressDecoder.decodeAddress(dstAddrType, in);
            final int dstPort = in.readUnsignedShort();

            out.add(new DefaultSocks5CommandRequest(type, dstAddrType, dstAddr, dstPort));
            checkpoint(State.SUCCESS);
        }
        case SUCCESS: {
            int readableBytes = actualReadableBytes();
            if (readableBytes > 0) {
                out.add(in.readRetainedSlice(readableBytes));
            }
            break;
        }
        case FAILURE: {
            in.skipBytes(actualReadableBytes());
            break;
        }
        }
    } catch (Exception e) {
        fail(out, e);
    }
}
 
Example 12
Source File: Socks4ClientDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    try {
        switch (state()) {
        case START: {
            final int version = in.readUnsignedByte();
            if (version != 0) {
                throw new DecoderException("unsupported reply version: " + version + " (expected: 0)");
            }

            final Socks4CommandStatus status = Socks4CommandStatus.valueOf(in.readByte());
            final int dstPort = in.readUnsignedShort();
            final String dstAddr = NetUtil.intToIpAddress(in.readInt());

            out.add(new DefaultSocks4CommandResponse(status, dstAddr, dstPort));
            checkpoint(State.SUCCESS);
        }
        case SUCCESS: {
            int readableBytes = actualReadableBytes();
            if (readableBytes > 0) {
                out.add(in.readRetainedSlice(readableBytes));
            }
            break;
        }
        case FAILURE: {
            in.skipBytes(actualReadableBytes());
            break;
        }
        }
    } catch (Exception e) {
        fail(out, e);
    }
}
 
Example 13
Source File: SSAddrRequest.java    From shadowsocks-java with MIT License 5 votes vote down vote up
public static SSAddrRequest getAddrRequest(ByteBuf byteBuf) {
    SSAddrRequest request = null;
    SocksAddressType addressType = SocksAddressType.valueOf(byteBuf.readByte());
    String host;
    int port;
    switch (addressType) {
        case IPv4: {
            host = SocksCommonUtils.intToIp(byteBuf.readInt());
            port = byteBuf.readUnsignedShort();
            request = new SSAddrRequest( addressType, host, port);
            break;
        }
        case DOMAIN: {
            int fieldLength = byteBuf.readByte();
            host = SocksCommonUtils.readUsAscii(byteBuf, fieldLength);
            port = byteBuf.readUnsignedShort();
            request = new SSAddrRequest( addressType, host, port);
            break;
        }
        case IPv6: {
            byte[] bytes = new byte[16];
            byteBuf.readBytes(bytes);
            host = SocksCommonUtils.ipv6toStr(bytes);
            port = byteBuf.readUnsignedShort();
            request = new SSAddrRequest(addressType, host, port);
            break;
        }
        case UNKNOWN:
            break;
    }
    return request;
}
 
Example 14
Source File: ForwardOpenResponse.java    From ethernet-ip with Apache License 2.0 5 votes vote down vote up
public static ForwardOpenResponse decode(ByteBuf buffer) {
    int o2tConnectionId = buffer.readInt();
    int t2oConnectionId = buffer.readInt();
    int connectionSerialNumber = buffer.readUnsignedShort();
    int originatorVendorId = buffer.readUnsignedShort();
    long originatorSerialNumber = buffer.readUnsignedInt();
    long o2tActualPacketInterval = TimeUnit.MICROSECONDS
        .convert(buffer.readUnsignedInt(), TimeUnit.MILLISECONDS);
    long t2oActualPacketInterval = TimeUnit.MICROSECONDS
        .convert(buffer.readUnsignedInt(), TimeUnit.MILLISECONDS);
    int applicationReplySize = buffer.readUnsignedByte();
    buffer.skipBytes(1); // reserved

    ByteBuf applicationReply = applicationReplySize > 0 ?
        buffer.readSlice(applicationReplySize).copy() :
        Unpooled.EMPTY_BUFFER;

    return new ForwardOpenResponse(
        o2tConnectionId,
        t2oConnectionId,
        connectionSerialNumber,
        originatorVendorId,
        originatorSerialNumber,
        Duration.ofMillis(o2tActualPacketInterval),
        Duration.ofMillis(t2oActualPacketInterval),
        applicationReplySize,
        applicationReply
    );
}
 
Example 15
Source File: NetFlowV9Parser.java    From graylog-plugin-netflow with Apache License 2.0 5 votes vote down vote up
/**
 * Options Template Format
 *
 * <pre>
 * |         FIELD         |                                                                                                                                                                                                                                          DESCRIPTION                                                                                                                                                                                                                                           |
 * |-----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
 * | flowset_id = 1        | The flowset_id is used to distinguish template records from data records. A template record always has a flowset_id of 1. A data record always has a nonzero flowset_id which is greater than 255.                                                                                                                                                                                                                                                                                             |
 * | length                | This field gives the total length of this FlowSet. Because an individual template FlowSet may contain multiple template IDs, the length value should be used to determine the position of the next FlowSet record, which could be either a template or a data FlowSet. Length is expressed in TLV format, meaning that the value includes the bytes used for the flowset_id and the length bytes themselves, as well as the combined lengths of all template records included in this FlowSet. |
 * | template_id           | As a router generates different template FlowSets to match the type of NetFlow data it will be exporting, each template is given a unique ID. This uniqueness is local to the router that generated the template_id. The template_id is greater than 255. Template IDs inferior to 255 are reserved.                                                                                                                                                                                           |
 * | option_scope_length   | This field gives the length in bytes of any scope fields contained in this options template (the use of scope is described below).                                                                                                                                                                                                                                                                                                                                                             |
 * | options_length        | This field gives the length (in bytes) of any Options field definitions contained in this options template.                                                                                                                                                                                                                                                                                                                                                                                    |
 * | scope_field_N_type    | This field gives the relevant portion of the NetFlow process to which the options record refers. Currently defined values follow:                                                                                                                                                                                                                                                                                                                                                              |
 * |                       | * 0x0001 System                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
 * |                       | * 0x0002 Interface                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
 * |                       | * 0x0003 Line Card                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
 * |                       | * 0x0004 NetFlow Cache                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
 * |                       | * 0x0005 Template                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
 * |                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
 * |                       | For example, sampled NetFlow can be implemented on a per-interface basis, so if the options record were reporting on how sampling is configured, the scope for the report would be 0x0002 (interface).                                                                                                                                                                                                                                                                                         |
 * | scope_field_N_length  | This field gives the length (in bytes) of the Scope field, as it would appear in an options record.                                                                                                                                                                                                                                                                                                                                                                                            |
 * | option_field_N_type   | This numeric value represents the type of the field that appears in the options record. Possible values are detailed in template flow set format (above).                                                                                                                                                                                                                                                                                                                                      |
 * | option_field_N_length | This number is the length (in bytes) of the field, as it would appear in an options record.                                                                                                                                                                                                                                                                                                                                                                                                    |
 * | padding               | Padding should be inserted to align the end of the FlowSet on a 32 bit boundary. Pay attention that the length field will include those padding bits.                                                                                                                                                                                                                                                                                                                                          |
 * </pre>
 */
public static NetFlowV9OptionTemplate parseOptionTemplate(ByteBuf bb, NetFlowV9FieldTypeRegistry typeRegistry) {
    int length = bb.readUnsignedShort();
    final int templateId = bb.readUnsignedShort();

    int optionScopeLength = bb.readUnsignedShort();
    int optionLength = bb.readUnsignedShort();

    int p = bb.readerIndex();
    int endOfScope = p + optionScopeLength;
    int endOfOption = endOfScope + optionLength;
    int endOfTemplate = p - 10 + length;

    final ImmutableList.Builder<NetFlowV9ScopeDef> scopeDefs = ImmutableList.builder();
    while (bb.readerIndex() < endOfScope) {
        int scopeType = bb.readUnsignedShort();
        int scopeLength = bb.readUnsignedShort();
        scopeDefs.add(NetFlowV9ScopeDef.create(scopeType, scopeLength));
    }

    // skip padding
    bb.readerIndex(endOfScope);

    final ImmutableList.Builder<NetFlowV9FieldDef> optionDefs = ImmutableList.builder();
    while (bb.readerIndex() < endOfOption) {
        int optType = bb.readUnsignedShort();
        int optLength = bb.readUnsignedShort();
        NetFlowV9FieldType t = typeRegistry.get(optType);
        optionDefs.add(NetFlowV9FieldDef.create(t, optLength));
    }

    // skip padding
    bb.readerIndex(endOfTemplate);

    return NetFlowV9OptionTemplate.create(templateId, scopeDefs.build(), optionDefs.build());
}
 
Example 16
Source File: Mqtt3PubcompDecoder.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Override
public PUBCOMP decode(final Channel channel, final ByteBuf buf, final byte header) {

    if (ProtocolVersion.MQTTv3_1_1 == channel.attr(MQTT_VERSION).get()) {
        if (!validateHeader(header)) {
            if (log.isDebugEnabled()) {
                log.debug("A client (IP: {}) sent a Pubcomp with an invalid fixed header. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
            }
            eventLog.clientWasDisconnected(channel, "Invalid PUBCOMP fixed header");
            channel.close();
            buf.clear();
            return null;
        }
    }

    if (buf.readableBytes() < 2) {
        if (log.isDebugEnabled()) {
            log.debug("A client (IP: {}) sent a Pubcomp without a message id. Disconnecting client.", getChannelIP(channel).or("UNKNOWN"));
        }
        eventLog.clientWasDisconnected(channel, "Sent PUBCOMP without message id");
        channel.close();
        buf.clear();
        return null;
    }
    final int messageId = buf.readUnsignedShort();

    return new PUBCOMP(messageId);
}
 
Example 17
Source File: SimpleBgpPrefixSidTlvRegistry.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public BgpPrefixSidTlv parseBgpPrefixSidTlv(final int type, final ByteBuf buffer) {
    final BgpPrefixSidTlvParser parser = this.handlers.getParser(type);
    if (parser == null) {
        return null;
    }
    final int length = buffer.readUnsignedShort();
    checkState(length <= buffer.readableBytes(),
            "Length of BGP prefix SID TLV exceeds readable bytes of income.");
    return parser.parseBgpPrefixSidTlv(buffer.readBytes(length));
}
 
Example 18
Source File: PacketHandshake.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void read(ByteBuf buf) {
    this.protocolVersion = MinecraftProtocol.readVarInt(buf);
    this.host = MinecraftProtocol.readString(buf, 255);
    this.port = buf.readUnsignedShort();
    this.nextState = MinecraftProtocol.readVarInt(buf) == 1 ? ProtocolState.STATUS : ProtocolState.LOGIN;
}
 
Example 19
Source File: SimpleNlriRegistry.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
private Class<? extends AddressFamily> getAfi(final ByteBuf buffer) throws BGPParsingException {
    final int afiVal = buffer.readUnsignedShort();
    final Class<? extends AddressFamily> afi = this.afiReg.classForFamily(afiVal);
    if (afi == null) {
        throw new BGPParsingException("Address Family Identifier: '" + afiVal + "' not supported.");
    }
    return afi;
}
 
Example 20
Source File: NetflowV9Decoder.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private int readUnsignedShortAndCheckpoint(ByteBuf buf) {
  final int val = buf.readUnsignedShort();
  parentDecoder.doCheckpoint();
  return val;
}