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

The following examples show how to use io.netty.buffer.ByteBuf#getUnsignedShort() .
Example 1
Project: netty-4.1.22   File: LengthFieldBasedFrameDecoder.java    License: 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
 * 将缓冲区的指定区域解码为未调整的帧长度。默认实现可以将指定的区域解码为无符号的8/16/24/32/64位整数。重写此方法,以不同的方式解码长度字段。注意,此方法不能修改指定缓冲区的状态(例如readerIndex、writerIndex和缓冲区的内容)。
 */
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 2
Project: hermes   File: HermesLengthFieldBasedFrameDecoder.java    License: 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 3
Project: vertx-sql-client   File: TdsPacketDecoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception {
  // decoding a packet
  if (in.readableBytes() > TdsPacket.PACKET_HEADER_SIZE) {
    int packetStartIdx = in.readerIndex();
    int packetLen = in.getUnsignedShort(packetStartIdx + 2);

    if (in.readableBytes() >= packetLen) {
      MessageType type = MessageType.valueOf(in.readUnsignedByte());
      MessageStatus status = MessageStatus.valueOf(in.readUnsignedByte());
      in.skipBytes(2); // packet length
      int processId = in.readUnsignedShort();
      short packetId = in.readUnsignedByte();
      in.skipBytes(1); // unused window

      ByteBuf packetData = in.readRetainedSlice(packetLen - TdsPacket.PACKET_HEADER_SIZE);

      list.add(TdsPacket.newTdsPacket(type, status, packetLen, processId, packetId, packetData));
    }
  }
}
 
Example 4
Project: graylog-plugin-netflow   File: ByteBufUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static long getUnsignedInteger(final ByteBuf buf, final int offset, final int length) {
    switch (length) {
        case 1:
            return buf.getUnsignedByte(offset);
        case 2:
            return buf.getUnsignedShort(offset);
        case 3:
            return buf.getUnsignedMedium(offset);
        case 4:
            return buf.getUnsignedInt(offset);
        case 8:
            return buf.getLong(offset) & 0x00000000ffffffffL;
        default:
            return 0L;
    }
}
 
Example 5
Project: netty4.0.27Learn   File: LengthFieldBasedFrameDecoder.java    License: 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 6
Project: opc-ua-stack   File: ChunkDecoder.java    License: Apache License 2.0 5 votes vote down vote up
private int getPaddingSize(int cipherTextBlockSize, int signatureSize, ByteBuf buffer) {
    int lastPaddingByteOffset = buffer.readableBytes() - signatureSize - 1;

    return cipherTextBlockSize <= 256 ?
            buffer.getUnsignedByte(lastPaddingByteOffset) + 1 :
            buffer.getUnsignedShort(lastPaddingByteOffset - 1) + 2;
}
 
Example 7
Project: plog   File: Fragment.java    License: Apache License 2.0 5 votes vote down vote up
public static Fragment fromDatagram(DatagramPacket packet) {
    final ByteBuf content = packet.content().order(ByteOrder.BIG_ENDIAN);

    final int length = content.readableBytes();
    if (length < HEADER_SIZE) {
        throw new IllegalArgumentException("Packet too short: " + length + " bytes");
    }

    final int fragmentCount = content.getUnsignedShort(2);
    if (fragmentCount == 0) {
        throw new IllegalArgumentException("0 fragment count");
    }

    final int fragmentIndex = content.getUnsignedShort(4);
    if (fragmentIndex >= fragmentCount) {
        throw new IllegalArgumentException("Index " + fragmentIndex + " < count " + fragmentCount);
    }

    final int fragmentSize = content.getUnsignedShort(6);
    final int idRightPart = content.getInt(8);
    final int totalLength = content.getInt(12);
    if (totalLength < 0) {
        throw new IllegalArgumentException("Cannot support length " + totalLength + " > 2^31");
    }

    final int msgHash = content.getInt(16);

    final int tagsBufferLength = content.getUnsignedShort(20);
    final ByteBuf tagsBuffer = tagsBufferLength == 0 ? null : content.slice(HEADER_SIZE, tagsBufferLength);

    final int payloadLength = length - HEADER_SIZE - tagsBufferLength;
    final ByteBuf payload = content.slice(HEADER_SIZE + tagsBufferLength, payloadLength);

    final int port = packet.sender().getPort();
    final long msgId = (((long) port) << Integer.SIZE) + idRightPart;

    return new Fragment(fragmentCount, fragmentIndex, fragmentSize, msgId, totalLength, msgHash, payload, tagsBuffer);
}
 
Example 8
Project: ethernet-ip   File: CpfItem.java    License: Apache License 2.0 5 votes vote down vote up
public static CpfItem decode(ByteBuf buffer) {
    int typeId = buffer.getUnsignedShort(buffer.readerIndex());

    switch (typeId) {
        case CipIdentityItem.TYPE_ID:
            return CipIdentityItem.decode(buffer);

        case ConnectedAddressItem.TYPE_ID:
            return ConnectedAddressItem.decode(buffer);

        case ConnectedDataItemResponse.TYPE_ID:
            return ConnectedDataItemResponse.decode(buffer);

        case NullAddressItem.TYPE_ID:
            return NullAddressItem.decode(buffer);

        case SequencedAddressItem.TYPE_ID:
            return SequencedAddressItem.decode(buffer);

        case SockAddrItemO2t.TYPE_ID:
            return SockAddrItemO2t.decode(buffer);

        case SockAddrItemT2o.TYPE_ID:
            return SockAddrItemT2o.decode(buffer);

        case UnconnectedDataItemResponse.TYPE_ID:
            return UnconnectedDataItemResponse.decode(buffer);

        default:
            throw new RuntimeException(String.format("unhandled item type: 0x%02X", typeId));
    }
}
 
Example 9
Project: jt808-server   File: JT808MessageDecoder.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 获取消息类型
 */
@Override
public int getType(ByteBuf source) {
    return source.getUnsignedShort(0);
}
 
Example 10
Project: onos   File: LispAfiAddress.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public LispAfiAddress readFrom(ByteBuf byteBuf)
                            throws LispParseError, LispReaderException {

    int index = byteBuf.readerIndex();

    // AFI code -> 16 bits
    short afiCode = (short) byteBuf.getUnsignedShort(index);

    // handle no address
    if (afiCode == NO_ADDRESS.getIanaCode()) {
        byteBuf.readUnsignedShort();
        return new LispNoAddress.NoAddressReader().readFrom(byteBuf);
    }

    // handle IPv4 and IPv6 address
    if (afiCode == IP4.getIanaCode() ||
        afiCode == IP6.getIanaCode()) {
        return new LispIpAddress.IpAddressReader().readFrom(byteBuf);
    }

    // handle distinguished name address
    if (afiCode == DISTINGUISHED_NAME.getIanaCode()) {
        return new LispDistinguishedNameAddress.DistinguishedNameAddressReader().readFrom(byteBuf);
    }

    // handle MAC address
    if (afiCode == MAC.getIanaCode()) {
        return new LispMacAddress.MacAddressReader().readFrom(byteBuf);
    }

    // handle LCAF address
    if (afiCode == LCAF.getIanaCode()) {
        return new LispLcafAddress.LcafAddressReader().readFrom(byteBuf);
    }

    // handle autonomous system address
    if (afiCode == AS.getIanaCode()) {
        return new LispAsAddress.AsAddressReader().readFrom(byteBuf);
    }

    return null;
}
 
Example 11
Project: bgpcep   File: PeerUpHandler.java    License: Eclipse Public License 1.0 4 votes vote down vote up
private static int getBgpMessageLength(final ByteBuf buffer) {
    return buffer.getUnsignedShort(buffer.readerIndex() + MessageUtil.MARKER_LENGTH);
}
 
Example 12
Project: netty-4.1.22   File: SslUtils.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static int unsignedShortBE(ByteBuf buffer, int offset) {
    return buffer.order() == ByteOrder.BIG_ENDIAN ?
            buffer.getUnsignedShort(offset) : buffer.getUnsignedShortLE(offset);
}
 
Example 13
Project: modbus   File: ModbusTcpCodec.java    License: Apache License 2.0 4 votes vote down vote up
private int getLength(ByteBuf in, int startIndex) {
    return in.getUnsignedShort(startIndex + LengthFieldIndex);
}
 
Example 14
Project: netty4.0.27Learn   File: SniHandler.java    License: Apache License 2.0 4 votes vote down vote up
private String sniHostNameFromHandshakeInfo(ByteBuf in) {
    int readerIndex = in.readerIndex();
    try {
        int command = in.getUnsignedByte(readerIndex);

        // tls, but not handshake command
        switch (command) {
            case SslConstants.SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
            case SslConstants.SSL_CONTENT_TYPE_ALERT:
            case SslConstants.SSL_CONTENT_TYPE_APPLICATION_DATA:
                return null;
            case SslConstants.SSL_CONTENT_TYPE_HANDSHAKE:
                break;
            default:
                //not tls or sslv3, do not try sni
                handshaken = true;
                return null;
        }

        int majorVersion = in.getUnsignedByte(readerIndex + 1);

        // SSLv3 or TLS
        if (majorVersion == 3) {

            int packetLength = in.getUnsignedShort(readerIndex + 3) + 5;

            if (in.readableBytes() >= packetLength) {
                // decode the ssl client hello packet
                // we have to skip some var-length fields
                int offset = readerIndex + 43;

                int sessionIdLength = in.getUnsignedByte(offset);
                offset += sessionIdLength + 1;

                int cipherSuitesLength = in.getUnsignedShort(offset);
                offset += cipherSuitesLength + 2;

                int compressionMethodLength = in.getUnsignedByte(offset);
                offset += compressionMethodLength + 1;

                int extensionsLength = in.getUnsignedShort(offset);
                offset += 2;
                int extensionsLimit = offset + extensionsLength;

                while (offset < extensionsLimit) {
                    int extensionType = in.getUnsignedShort(offset);
                    offset += 2;

                    int extensionLength = in.getUnsignedShort(offset);
                    offset += 2;

                    // SNI
                    if (extensionType == 0) {
                        handshaken = true;
                        int serverNameType = in.getUnsignedByte(offset + 2);
                        if (serverNameType == 0) {
                            int serverNameLength = in.getUnsignedShort(offset + 3);
                            return in.toString(offset + 5, serverNameLength,
                                    CharsetUtil.UTF_8);
                        } else {
                            // invalid enum value
                            return null;
                        }
                    }

                    offset += extensionLength;
                }

                handshaken = true;
                return null;
            } else {
                // client hello incomplete
                return null;
            }
        } else {
            handshaken = true;
            return null;
        }
    } catch (Throwable e) {
        // unexpected encoding, ignore sni and use default
        if (logger.isDebugEnabled()) {
            logger.debug("Unexpected client hello packet: " + ByteBufUtil.hexDump(in), e);
        }
        handshaken = true;
        return null;
    }
}
 
Example 15
Project: riiablo   File: Packet.java    License: Apache License 2.0 4 votes vote down vote up
public static int getSEQ(ByteBuf bb) {
  return bb.getUnsignedShort(SEQ_OFFSET);
}
 
Example 16
Project: riiablo   File: Packet.java    License: Apache License 2.0 4 votes vote down vote up
public static int getContentSize(ByteBuf bb) {
  return bb.getUnsignedShort(CONTENT_SIZE_OFFSET);
}
 
Example 17
Project: riiablo   File: Packet.java    License: Apache License 2.0 4 votes vote down vote up
public static int getFragmentSize(ByteBuf bb) {
  return bb.getUnsignedShort(FRAGSIZE_OFFSET);
}
 
Example 18
Project: riiablo   File: Packet.java    License: Apache License 2.0 4 votes vote down vote up
public static int getSliceSize(ByteBuf bb) {
  return bb.getUnsignedShort(SLICESIZE_OFFSET);
}
 
Example 19
Project: datacollector   File: CollectdParser.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Parses a collectd packet "part".
 *
 * @param startOffset beginning offset for this part
 * @param buf         buffered packet
 * @param fields      field map for the output record
 * @return offset after consuming part
 */
private int parsePart(int startOffset, ByteBuf buf, Map<String, Field> fields) throws OnRecordErrorException {
  int offset = startOffset;
  int type = buf.getUnsignedShort(offset); // 0-1
  offset += 2;
  final int length = buf.getUnsignedShort(offset); // 2-3
  offset += 2;

  switch (type) {
    case HOST:
    case PLUGIN:
    case PLUGIN_INSTANCE:
    case TYPE:
    case TYPE_INSTANCE:
    case MESSAGE:
      pruneFields(type);
      fields.put(PART_TYPES.get(type), Field.create(parseString(offset, length, buf)));
      offset += length - 4;
      break;
    case TIME_HIRES:
    case INTERVAL_HIRES:
      if (type != INTERVAL_HIRES || !excludeInterval) {
        long value = parseNumeric(offset, buf);
        if (convertTime) {
          value *= (Math.pow(2, -30) * 1000);
          type = type == TIME_HIRES ? TIME : INTERVAL;
        }
        fields.put(PART_TYPES.get(type), Field.create(value));
      }
      offset += 8;
      break;
    case TIME:
    case INTERVAL:
    case SEVERITY:
      if (type != INTERVAL || !excludeInterval) {
        fields.put(PART_TYPES.get(type), Field.create(parseNumeric(offset, buf)));
      }
      offset += 8;
      break;
    case VALUES:
      offset = parseValues(offset, buf);
      startNewRecord();
      break;
    case SIGNATURE:
      if (!verifySignature(offset, length, buf)) {
        throw new OnRecordErrorException(Errors.COLLECTD_02);
      }
      offset += length - 4;
      break;
    case ENCRYPTION:
      String user = parseUser(offset, buf);
      offset += (2 + user.length());
      byte[] iv = parseIv(offset, buf);
      offset += 16;
      decrypt(offset, length, buf, user, iv);
      // Skip the checksum and continue processing.
      offset += 20;
      break;
    default:
      // Don't recognize this part type, so skip it
      LOG.warn("Unrecognized part type: {}", type);
      offset += length - 4;
      break;
  }

  return offset;
}
 
Example 20
Project: datacollector   File: CollectdParser.java    License: Apache License 2.0 4 votes vote down vote up
private String parseUser(int offset, ByteBuf buf) {
  int userLength = buf.getUnsignedShort(offset);
  byte[] userBytes = new byte[userLength];
  buf.getBytes(offset + 2, userBytes, 0, userLength);
  return new String(userBytes, StandardCharsets.UTF_8);
}