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

The following examples show how to use io.netty.buffer.ByteBuf#readUnsignedByte() . 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: TextSerializer_v332.java    From Protocol with Apache License 2.0 6 votes vote down vote up
@Override
public void deserialize(ByteBuf buffer, TextPacket packet) {
    TextPacket.Type type = TextPacket.Type.values()[buffer.readUnsignedByte()];
    packet.setType(type);
    packet.setNeedsTranslation(buffer.readBoolean());
    switch (type) {
        case CHAT:
        case WHISPER:
        case ANNOUNCEMENT:
            packet.setSourceName(BedrockUtils.readString(buffer));
        case RAW:
        case TIP:
        case SYSTEM:
            packet.setMessage(BedrockUtils.readString(buffer));
            break;
        case TRANSLATION:
        case POPUP:
        case JUKEBOX_POPUP:
            packet.setMessage(BedrockUtils.readString(buffer));
            BedrockUtils.readArray(buffer, packet.getParameters(), BedrockUtils::readString);
            break;
    }
    packet.setXuid(BedrockUtils.readString(buffer));
    packet.setPlatformChatId(BedrockUtils.readString(buffer));
}
 
Example 2
Source File: GracefulCapabilityHandler.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public CParameters parseCapability(final ByteBuf buffer) throws BGPDocumentedException, BGPParsingException {
    final GracefulRestartCapabilityBuilder cb = new GracefulRestartCapabilityBuilder();

    final int flagBits = buffer.getByte(0) >> RESTART_FLAGS_SIZE;
    cb.setRestartFlags(new RestartFlags((flagBits & Byte.SIZE) != 0));

    final int timer = ((buffer.readUnsignedByte() & TIMER_TOPBITS_MASK) << Byte.SIZE) + buffer.readUnsignedByte();
    cb.setRestartTime(Uint16.valueOf(timer));

    final List<Tables> tables = new ArrayList<>();
    while (buffer.readableBytes() != 0) {
        final int afiVal = buffer.readShort();
        final Class<? extends AddressFamily> afi = this.afiReg.classForFamily(afiVal);
        if (afi == null) {
            LOG.debug("Ignoring GR capability for unknown address family {}", afiVal);
            buffer.skipBytes(PER_AFI_SAFI_SIZE - 2);
            continue;
        }
        final int safiVal = buffer.readUnsignedByte();
        final Class<? extends SubsequentAddressFamily> safi = this.safiReg.classForFamily(safiVal);
        if (safi == null) {
            LOG.debug("Ignoring GR capability for unknown subsequent address family {}", safiVal);
            buffer.skipBytes(1);
            continue;
        }
        final int flags = buffer.readUnsignedByte();
        tables.add(new TablesBuilder().setAfi(afi).setSafi(safi)
            .setAfiFlags(new AfiFlags((flags & AFI_FLAG_FORWARDING_STATE) != 0)).build());
    }
    cb.setTables(tables);
    return new CParametersBuilder()
            .addAugmentation(new CParameters1Builder().setGracefulRestartCapability(cb.build()).build())
            .build();
}
 
Example 3
Source File: MqttDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static Result<Integer> decodeMsbLsb(ByteBuf buffer, int min, int max) {
    short msbSize = buffer.readUnsignedByte();
    short lsbSize = buffer.readUnsignedByte();
    final int numberOfBytesConsumed = 2;
    int result = msbSize << 8 | lsbSize;
    if (result < min || result > max) {
        result = -1;
    }
    return new Result<Integer>(result, numberOfBytesConsumed);
}
 
Example 4
Source File: ChunkSectionType1_13.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public ChunkSection read(ByteBuf buffer) throws Exception {
    ChunkSection chunkSection = new ChunkSection();

    // Reaad bits per block
    int bitsPerBlock = buffer.readUnsignedByte();
    int originalBitsPerBlock = bitsPerBlock;

    if (bitsPerBlock == 0 || bitsPerBlock > 8) {
        bitsPerBlock = GLOBAL_PALETTE;
    }

    int paletteLength = bitsPerBlock == GLOBAL_PALETTE ? 0 : Type.VAR_INT.readPrimitive(buffer);
    // Read palette
    chunkSection.clearPalette();
    for (int i = 0; i < paletteLength; i++) {
        chunkSection.addPaletteEntry(Type.VAR_INT.readPrimitive(buffer));
    }

    // Read blocks
    long[] blockData = new long[Type.VAR_INT.readPrimitive(buffer)];
    if (blockData.length > 0) {
        int expectedLength = (int) Math.ceil(ChunkSection.SIZE * bitsPerBlock / 64.0);
        if (blockData.length != expectedLength) {
            throw new IllegalStateException("Block data length (" + blockData.length + ") does not match expected length (" + expectedLength + ")! bitsPerBlock=" + bitsPerBlock + ", originalBitsPerBlock=" + originalBitsPerBlock);
        }

        for (int i = 0; i < blockData.length; i++) {
            blockData[i] = buffer.readLong();
        }
        CompactArrayUtil.iterateCompactArray(bitsPerBlock, ChunkSection.SIZE, blockData,
                bitsPerBlock == GLOBAL_PALETTE ? chunkSection::setFlatBlock : chunkSection::setPaletteIndex);
    }

    return chunkSection;
}
 
Example 5
Source File: MiddleScoreboardScore.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void readServerData(ByteBuf serverdata) {
	name = StringSerializer.readVarIntUTF8String(serverdata);
	mode = serverdata.readUnsignedByte();
	objectiveName = StringSerializer.readVarIntUTF8String(serverdata);
	if (mode != 1) {
		value = VarNumberSerializer.readVarInt(serverdata);
	}
}
 
Example 6
Source File: MoveEntityAbsoluteSerializer_v332.java    From Protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void deserialize(ByteBuf buffer, MoveEntityAbsolutePacket packet) {
    packet.setRuntimeEntityId(VarInts.readUnsignedLong(buffer));
    int flags = buffer.readUnsignedByte();
    packet.setOnGround((flags & FLAG_ON_GROUND) != 0);
    packet.setTeleported((flags & FLAG_TELEPORTED) != 0);
    packet.setPosition(BedrockUtils.readVector3f(buffer));
    packet.setRotation(BedrockUtils.readByteRotation(buffer));
}
 
Example 7
Source File: LongCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static long decodeBinary(ByteBuf buf, short type, boolean isUnsigned) {
    switch (type) {
        case DataTypes.BIGINT:
            // Note: no check overflow for BIGINT UNSIGNED
            return buf.readLongLE();
        case DataTypes.INT:
            if (isUnsigned) {
                return buf.readUnsignedIntLE();
            } else {
                return buf.readIntLE();
            }
        case DataTypes.MEDIUMINT:
            // Note: MySQL return 32-bits two's complement for 24-bits integer
            return buf.readIntLE();
        case DataTypes.SMALLINT:
            if (isUnsigned) {
                return buf.readUnsignedShortLE();
            } else {
                return buf.readShortLE();
            }
        case DataTypes.YEAR:
            return buf.readShortLE();
        default: // TINYINT
            if (isUnsigned) {
                return buf.readUnsignedByte();
            } else {
                return buf.readByte();
            }
    }
}
 
Example 8
Source File: ResultPacketCodec.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
public ResultPacket decode(ByteBuf buffer) throws Exception {
	int id = buffer.readInt();
	int statusCode = buffer.readUnsignedByte();
	if(statusCode == ConnectPacketConstants.statusSuccess) {
		return new ResultPacket(id, buffer.readBytes(buffer.readUnsignedShort()));
	} else {
		return new ResultPacket(id, statusCode);
	}
}
 
Example 9
Source File: SetScoreboardIdentitySerializer_v332.java    From Protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void deserialize(ByteBuf buffer, SetScoreboardIdentityPacket packet) {
    SetScoreboardIdentityPacket.Action action = SetScoreboardIdentityPacket.Action.values()[buffer.readUnsignedByte()];
    packet.setAction(action);
    BedrockUtils.readArray(buffer, packet.getEntries(), buf -> {
        long scoreboardId = VarInts.readLong(buffer);
        UUID uuid = null;
        if (action == Action.ADD) {
            uuid = BedrockUtils.readUuid(buffer);
        }
        return new Entry(scoreboardId, uuid);
    });
}
 
Example 10
Source File: MySQLJsonValueDecoder.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static int decodeDataLength(final ByteBuf byteBuf) {
    int length = 0;
    for (int i = 0; ; i++) {
        int data = byteBuf.readUnsignedByte();
        length |= (data & 0x7f) << (7 * i);
        if (0 == (data & 0x80)) {
            break;
        }
    }
    return length;
}
 
Example 11
Source File: Snappy.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Reads a literal from the input buffer directly to the output buffer.
 * A "literal" is an uncompressed segment of data stored directly in the
 * byte stream.从输入缓冲区直接读入输出缓冲区。“文字”是直接存储在字节流中的未压缩数据段。
 *
 * @param tag The tag that identified this segment as a literal is also
 *            used to encode part of the length of the data
 * @param in The input buffer to read the literal from
 * @param out The output buffer to write the literal to
 * @return The number of bytes appended to the output buffer, or -1 to indicate "try again later"
 */
static int decodeLiteral(byte tag, ByteBuf in, ByteBuf out) {
    in.markReaderIndex();
    int length;
    switch(tag >> 2 & 0x3F) {
    case 60:
        if (!in.isReadable()) {
            return NOT_ENOUGH_INPUT;
        }
        length = in.readUnsignedByte();
        break;
    case 61:
        if (in.readableBytes() < 2) {
            return NOT_ENOUGH_INPUT;
        }
        length = in.readUnsignedShortLE();
        break;
    case 62:
        if (in.readableBytes() < 3) {
            return NOT_ENOUGH_INPUT;
        }
        length = in.readUnsignedMediumLE();
        break;
    case 63:
        if (in.readableBytes() < 4) {
            return NOT_ENOUGH_INPUT;
        }
        length = in.readIntLE();
        break;
    default:
        length = tag >> 2 & 0x3F;
    }
    length += 1;

    if (in.readableBytes() < length) {
        in.resetReaderIndex();
        return NOT_ENOUGH_INPUT;
    }

    out.writeBytes(in, length);
    return length;
}
 
Example 12
Source File: PingHandshakePacket.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void read0(ByteBuf from) {
	from.readUnsignedByte();
}
 
Example 13
Source File: Socks4ServerDecoder.java    From netty-4.1.22 with Apache License 2.0 4 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 != SocksVersion.SOCKS4a.byteValue()) {
                throw new DecoderException("unsupported protocol version: " + version);
            }

            type = Socks4CommandType.valueOf(in.readByte());
            dstPort = in.readUnsignedShort();
            dstAddr = NetUtil.intToIpAddress(in.readInt());
            checkpoint(State.READ_USERID);
        }
        case READ_USERID: {
            userId = readString("userid", in);
            checkpoint(State.READ_DOMAIN);
        }
        case READ_DOMAIN: {
            // Check for Socks4a protocol marker 0.0.0.x
            if (!"0.0.0.0".equals(dstAddr) && dstAddr.startsWith("0.0.0.")) {
                dstAddr = readString("dstAddr", in);
            }
            out.add(new DefaultSocks4CommandRequest(type, dstAddr, dstPort, userId));
            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 14
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Throw away read unsigned bytes.
 *
 * @param buffer the buffer
 */
private void throwAwayReadUnsignedBytes(ByteBuf buffer) {
	buffer.readUnsignedByte();
	buffer.readUnsignedByte();
	buffer.readUnsignedByte();
}
 
Example 15
Source File: SteerVehicle.java    From ProtocolSupport with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void readClientData(ByteBuf clientdata) {
	sideForce = clientdata.readFloat();
	forwardForce = clientdata.readFloat();
	flags = clientdata.readUnsignedByte();
}
 
Example 16
Source File: InitialHandshakeCommandCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private void handleInitialHandshake(ByteBuf payload) {
  encoder.clientCapabilitiesFlag = cmd.initialCapabilitiesFlags();
  encoder.encodingCharset = cmd.charsetEncoding();
  short protocolVersion = payload.readUnsignedByte();

  String serverVersion = BufferUtils.readNullTerminatedString(payload, StandardCharsets.US_ASCII);
  MySQLDatabaseMetadata md = MySQLDatabaseMetadata.parse(serverVersion);
  encoder.socketConnection.metaData = md;
  if (md.majorVersion() == 5 &&
      (md.minorVersion() < 7 || (md.minorVersion() == 7 && md.microVersion() < 5))) {
    // EOF_HEADER has to be enabled for older MySQL version which does not support the CLIENT_DEPRECATE_EOF flag
  } else {
    encoder.clientCapabilitiesFlag |= CLIENT_DEPRECATE_EOF;
  }

  long connectionId = payload.readUnsignedIntLE();

  // read first part of scramble
  this.authPluginData = new byte[NONCE_LENGTH];
  payload.readBytes(authPluginData, 0, AUTH_PLUGIN_DATA_PART1_LENGTH);

  //filler
  payload.readByte();

  // read lower 2 bytes of Capabilities flags
  int lowerServerCapabilitiesFlags = payload.readUnsignedShortLE();

  short characterSet = payload.readUnsignedByte();

  int statusFlags = payload.readUnsignedShortLE();

  // read upper 2 bytes of Capabilities flags
  int capabilityFlagsUpper = payload.readUnsignedShortLE();
  final int serverCapabilitiesFlags = (lowerServerCapabilitiesFlags | (capabilityFlagsUpper << 16));

  // length of the combined auth_plugin_data (scramble)
  short lenOfAuthPluginData;
  boolean isClientPluginAuthSupported = (serverCapabilitiesFlags & CapabilitiesFlag.CLIENT_PLUGIN_AUTH) != 0;
  if (isClientPluginAuthSupported) {
    lenOfAuthPluginData = payload.readUnsignedByte();
  } else {
    payload.readerIndex(payload.readerIndex() + 1);
    lenOfAuthPluginData = 0;
  }

  // 10 bytes reserved
  payload.readerIndex(payload.readerIndex() + 10);

  // Rest of the plugin provided data
  payload.readBytes(authPluginData, AUTH_PLUGIN_DATA_PART1_LENGTH, Math.max(NONCE_LENGTH - AUTH_PLUGIN_DATA_PART1_LENGTH, lenOfAuthPluginData - 9));
  payload.readByte(); // reserved byte

  // we assume the server supports auth plugin
  final String authPluginName = BufferUtils.readNullTerminatedString(payload, StandardCharsets.UTF_8);

  boolean upgradeToSsl;
  SslMode sslMode = cmd.sslMode();
  switch (sslMode) {
    case DISABLED:
      upgradeToSsl = false;
      break;
    case PREFERRED:
      upgradeToSsl = isTlsSupportedByServer(serverCapabilitiesFlags);
      break;
    case REQUIRED:
    case VERIFY_CA:
    case VERIFY_IDENTITY:
      upgradeToSsl = true;
      break;
    default:
      completionHandler.handle(CommandResponse.failure(new IllegalStateException("Unknown SSL mode to handle: " + sslMode)));
      return;
  }

  if (upgradeToSsl) {
    encoder.clientCapabilitiesFlag |= CLIENT_SSL;
    sendSslRequest();

    encoder.socketConnection.upgradeToSsl(upgrade -> {
      if (upgrade.succeeded()) {
        doSendHandshakeResponseMessage(authPluginName, authPluginData, serverCapabilitiesFlags);
      } else {
        completionHandler.handle(CommandResponse.failure(upgrade.cause()));
      }
    });
  } else {
    doSendHandshakeResponseMessage(authPluginName, authPluginData, serverCapabilitiesFlags);
  }
}
 
Example 17
Source File: InitialPacketDecoder.java    From ProtocolSupport with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void decodeEncapsulated(ChannelHandlerContext ctx) throws Exception {
	Channel channel = ctx.channel();
	ByteBuf firstpacketdata = buffer.readSlice(VarNumberSerializer.readVarInt(buffer));
	if (encapsulatedinfo.hasCompression()) {
		int uncompressedlength = VarNumberSerializer.readVarInt(firstpacketdata);
		if (uncompressedlength != 0) {
			firstpacketdata = Unpooled.wrappedBuffer(Decompressor.decompressStatic(MiscSerializer.readAllBytes(firstpacketdata), uncompressedlength));
		}
	}
	int firstbyte = firstpacketdata.readUnsignedByte();
	switch (firstbyte) {
		case 0xFE: { //legacy ping
			if (firstpacketdata.readableBytes() == 0) {
				//< 1.5.2
				setProtocol(channel, ProtocolVersion.MINECRAFT_LEGACY);
			} else if (firstpacketdata.readUnsignedByte() == 1) {
				//1.5 or 1.6 ping
				if (firstpacketdata.readableBytes() == 0) {
					//1.5.*, we just assume 1.5.2
					setProtocol(channel, ProtocolVersion.MINECRAFT_1_5_2);
				} else if (
					(firstpacketdata.readUnsignedByte() == 0xFA) &&
					"MC|PingHost".equals(StringSerializer.readShortUTF16BEString(firstpacketdata, Short.MAX_VALUE))
				) {
					//1.6.*
					firstpacketdata.readUnsignedShort();
					setProtocol(channel, ProtocolUtils.get16PingVersion(firstpacketdata.readUnsignedByte()));
				} else {
					throw new DecoderException("Unable to detect incoming protocol");
				}
			} else {
				throw new DecoderException("Unable to detect incoming protocol");
			}
			break;
		}
		case 0x02: { // <= 1.6.4 handshake
			setProtocol(channel, ProtocolUtils.readOldHandshake(firstpacketdata));
			break;
		}
		case 0x00: { // >= 1.7 handshake
			setProtocol(channel, ProtocolUtils.readNewHandshake(firstpacketdata));
			break;
		}
		default: {
			throw new DecoderException("Unable to detect incoming protocol");
		}
	}
}
 
Example 18
Source File: MuCryptUtils.java    From vethrfolnir-mu with GNU General Public License v3.0 4 votes vote down vote up
public static final void readAsUByteArray(ByteBuf buff, short[] uByteArray) {
	for (int i = 0; i < uByteArray.length; i++) {
		uByteArray[i] = buff.readUnsignedByte();
	}
}
 
Example 19
Source File: PlayerAbilities.java    From ProtocolSupport with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void readClientData(ByteBuf clientdata) {
	flags = clientdata.readUnsignedByte();
	clientdata.skipBytes(Float.BYTES * 2); //fly+walk speeds
}
 
Example 20
Source File: MessageDecoder.java    From asteria-3.0 with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Decode the message opcode and determine the message type. If the message
 * is variable sized set the next state to {@code SIZE}, otherwise set it to
 * {@code PAYLOAD}.
 * 
 * @param ctx
 *            the context for our channel, used to retrieve the session
 *            instance.
 * @param msg
 *            the message to decode the opcode from.
 * @return an optional containing a message with no payload, or an empty
 *         optional.
 */
private Optional<InputMessage> opcode(ChannelHandlerContext ctx, ByteBuf msg) {
    if (msg.isReadable()) {
        opcode = msg.readUnsignedByte();
        opcode = (opcode - decryptor.getKey()) & 0xFF;
        size = NetworkConstants.MESSAGE_SIZES[opcode];
        if (size == 0)
            return message(ctx, Unpooled.EMPTY_BUFFER);
        state = size == NetworkConstants.VAR_SIZE || size == NetworkConstants.VAR_SIZE_SHORT ? State.SIZE : State.PAYLOAD;
    }
    return Optional.empty();
}