Example usage for io.netty.buffer ByteBuf readUnsignedByte

List of usage examples for io.netty.buffer ByteBuf readUnsignedByte

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readUnsignedByte.

Prototype

public abstract short readUnsignedByte();

Source Link

Document

Gets an unsigned byte at the current readerIndex and increases the readerIndex by 1 in this buffer.

Usage

From source file:org.graylog.plugins.netflow.utils.ByteBufUtils.java

License:Apache License

public static InetAddress getInetAddress(final ByteBuf buf, final int offset, final int length) {
    final ByteBuf buffer = buf.slice(offset, length);

    final byte[] data = new byte[length];
    for (int i = 1; i <= length; i++) {
        data[i - 1] = (byte) buffer.readUnsignedByte();
    }/*from  w w w  .  ja  va2 s  . c  om*/

    InetAddress address;
    try {
        address = InetAddress.getByAddress(data);
    } catch (UnknownHostException e) {
        address = DEFAULT_INET_ADDRESS;
    }

    return address;
}

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClient33Decoder.java

License:Apache License

protected PixelFormat parsePixelFormat(ByteBuf m) {

    PixelFormat pf = new PixelFormat();

    pf.setBitPerPixel(m.readUnsignedByte());
    pf.setDepth(m.readUnsignedByte());/*from   w w w  .j  a  v  a 2 s  .  c  o m*/
    pf.setBigEndian(m.readUnsignedByte() == 1);
    pf.setTrueColor(m.readUnsignedByte() == 1);
    pf.setRedMax(m.readUnsignedShort());
    pf.setGreenMax(m.readUnsignedShort());
    pf.setBlueMax(m.readUnsignedShort());

    pf.setRedShift(m.readUnsignedByte());
    pf.setGreenShift(m.readUnsignedByte());
    pf.setBlueShift(m.readUnsignedByte());
    m.skipBytes(3);

    return pf;
}

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClient38Decoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (state()) {
    case SEC_TYPES:
        int numberOfSecurtiyTypes = in.readUnsignedByte();
        if (numberOfSecurtiyTypes == 0) {
            logger.error("no security types available");
            decodeErrorMessage(ctx, in);
            return;
        }/*from   ww w . j  a va2 s . c  o m*/
        SecurityType[] serverSecTypes = new SecurityType[numberOfSecurtiyTypes];
        for (int i = 0; i < numberOfSecurtiyTypes; i++) {
            int sec = in.readUnsignedByte();
            serverSecTypes[i] = SecurityType.valueOf(sec);
            if (serverSecTypes[i] == SecurityType.UNKNOWN) {
                logger.error("un supported security types: {}", sec);
            }
        }
        logger.debug("supported security types: {}", Arrays.toString(serverSecTypes));
        checkpoint(State.SEC_RESULT);
        out.add(new SecurityTypesEvent(true, serverSecTypes));
        break;
    case SEC_RESULT:

        int secResult = in.readInt();
        logger.debug("server login {}", secResult == 0 ? "succeed" : "failed");
        if (secResult == 1) {
            int length = in.readInt();
            if (length == 0) {
                out.add(new SecurityResultEvent(false, new ProtocolException("decode error message failed")));
                return;
            }
            byte[] text = new byte[length];
            in.readBytes(text);
            out.add(new SecurityResultEvent(false, new SecurityException(new String(text, ASCII))));
            return;
        }
        out.add(new SecurityResultEvent(true));
        checkpoint(State.SERVER_INIT);
        break;
    case SERVER_INIT:
        ServerInitEvent initMsg = new ServerInitEvent();

        initMsg.setFrameBufferWidth(in.readUnsignedShort());
        initMsg.setFrameBufferHeight(in.readUnsignedShort());

        initMsg.setPixelFormat(parsePixelFormat(in));

        byte[] name = new byte[in.readInt()];
        in.readBytes(name);

        initMsg.setServerName(new String(name, ASCII));
        out.add(initMsg);
        break;
    default:
        break;

    }
}

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClient38Decoder.java

License:Apache License

private PixelFormat parsePixelFormat(ByteBuf m) {

    PixelFormat pf = new PixelFormat();

    pf.setBitPerPixel(m.readUnsignedByte());
    pf.setDepth(m.readUnsignedByte());//from  w  w w . jav  a2  s  .c  o  m
    pf.setBigEndian(m.readUnsignedByte() == 1);
    pf.setTrueColor(m.readUnsignedByte() == 1);
    pf.setRedMax(m.readUnsignedShort());
    pf.setGreenMax(m.readUnsignedShort());
    pf.setBlueMax(m.readUnsignedShort());

    pf.setRedShift(m.readUnsignedByte());
    pf.setGreenShift(m.readUnsignedByte());
    pf.setBlueShift(m.readUnsignedByte());
    m.skipBytes(3);

    return pf;
}

From source file:org.l2junity.network.codecs.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if ((in == null) || !in.isReadable()) {
        return;/*  w  w  w. j  av a 2  s  .  c  o m*/
    }

    if (in.order() != _byteOrder) {
        in = in.order(_byteOrder);
    }

    try {
        final short packetId = in.readUnsignedByte();
        if (packetId >= _incomingPackets.length) {
            LOGGER.debug("Unknown packet: {}", Integer.toHexString(packetId));
            return;
        }

        final IIncomingPackets<T> incomingPacket = _incomingPackets[packetId];
        if (incomingPacket == null) {
            LOGGER.debug("Unknown packet: {}", Integer.toHexString(packetId));
            return;
        }

        final IConnectionState connectionState = ctx.channel().attr(IConnectionState.ATTRIBUTE_KEY).get();
        if ((connectionState == null) || !incomingPacket.getConnectionStates().contains(connectionState)) {
            LOGGER.warn("{}: Connection at invalid state: {} Required States: {}", incomingPacket,
                    connectionState, incomingPacket.getConnectionStates());
            return;
        }

        final IIncomingPacket<T> packet = incomingPacket.newIncomingPacket();
        if ((packet != null) && packet.read(_client, new PacketReader(in))) {
            out.add(packet);
        }
    } finally {
        // We always consider that we read whole packet.
        in.readerIndex(in.writerIndex());
    }
}

From source file:org.lanternpowered.pingy.PingyLegacyHandler.java

License:MIT License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg0) throws Exception {
    final ByteBuf msg = (ByteBuf) msg0;

    boolean legacy = false;
    msg.markReaderIndex();/*w w  w  .  j a  va  2 s .c  om*/
    try {
        // Try first as a legacy ping message
        int messageId = msg.readUnsignedByte();
        // Make sure that old clients don't attempt to login
        if (messageId == 0x02) {
            legacy = this.tryHandleLegacyJoin(ctx, msg);
        } else if (messageId == 0xfe) {
            legacy = this.tryHandleLegacyPing(ctx, msg);
        }
    } catch (Exception e) {
    }
    if (!legacy) {
        msg.resetReaderIndex();
        ctx.pipeline().remove(this);
        ctx.fireChannelRead(msg);
    } else {
        msg.release();
    }
}

From source file:org.lanternpowered.pingy.PingyLegacyHandler.java

License:MIT License

private boolean tryHandleLegacyPing(ChannelHandlerContext ctx, ByteBuf msg) {
    int readable = msg.readableBytes();

    // Full message, contains more info
    boolean full = false;

    if (readable > 0) {
        // Is always 1
        if (msg.readUnsignedByte() != 1) {
            return false;
        }//from  ww w  .j  a  v a2 s.  c o  m
        full = true;
    }

    if (readable > 1) {
        if (msg.readUnsignedByte() != 0xfa) {
            return false;
        }
        byte[] bytes = new byte[msg.readShort() << 1];
        msg.readBytes(bytes);
        if (!new String(bytes, StandardCharsets.UTF_16BE).equals("MC|PingHost")) {
            return false;
        }
    }

    final String motd = getFirstLine(this.properties.getLegacyMessageOfTheDay());
    if (full) {
        sendLegacyDisconnectMessage(ctx, String.format("\u00A7%s\0%s\0%s\0%s\0%s\0%s", 1, 127,
                this.properties.getOutdatedMessage(), motd, -1, -1));
    } else {
        sendLegacyDisconnectMessage(ctx, String.format("%s\u00A7%s\u00A7%s", motd, -1, -1));
    }

    return true;
}

From source file:org.lanternpowered.server.network.pipeline.LegacyProtocolHandler.java

License:MIT License

@Override
public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception {
    final LanternServer server = this.session.getServer();

    ByteBuf buf = (ByteBuf) object;
    buf.markReaderIndex();/* w  ww.  j  a  v a 2 s  . c  o  m*/

    // Whether it was a valid legacy message
    boolean legacy = false;

    try {
        final int messageId = buf.readUnsignedByte();
        // Old client's are not so smart, make sure that
        // they don't attempt to login
        if (messageId == 0x02) {
            int protocol = buf.readByte(); // Protocol version
            int value = buf.readShort();
            // Check the length
            if (value < 0 || value > 16) {
                return;
            }
            buf.readBytes(value << 1); // Username
            value = buf.readShort();
            // Check the length
            if (value < 0 || value > 255) {
                return;
            }
            buf.readBytes(value << 1); // Host address
            buf.readInt(); // Port
            if (buf.readableBytes() > 0) {
                return;
            }
            legacy = true;
            sendDisconnectMessage(ctx, LanternTexts.toPlain(t("multiplayer.disconnect.outdated_client",
                    Lantern.getGame().getPlatform().getMinecraftVersion().getName())));
            final MinecraftVersion clientVersion = Lantern.getGame().getMinecraftVersionCache()
                    .getVersionOrUnknown(protocol, true);
            if (clientVersion == LanternMinecraftVersion.UNKNOWN_LEGACY) {
                Lantern.getLogger().debug(
                        "Client with unknown legacy protocol version {} attempted to join the server.",
                        protocol);
            } else {
                Lantern.getLogger().debug(
                        "Client with legacy protocol version {} (mc-version {}) attempted to join the server.",
                        protocol, clientVersion.getName());
            }
            return;
        }

        // Check for the ping message id.
        if (messageId != 0xfe) {
            return;
        }

        int readable = buf.readableBytes();
        boolean full = false;

        // The version used to ping the server
        int protocol = V1_3_2_PROTOCOL;

        // Versions 1.4 - 1.5.x + 1.6 - Can request full data.
        if (readable > 0) {
            // Is always 1
            if (buf.readUnsignedByte() != 1) {
                return;
            }
            full = true;
            protocol = V1_5_2_PROTOCOL;
        }

        // The virtual address that was used to join the server
        InetSocketAddress virtualAddress = null;

        // Version 1.6 - Used extra data.
        if (readable > 1) {
            if (buf.readUnsignedByte() != 0xfa) {
                return;
            }
            byte[] bytes = new byte[buf.readShort() << 1];
            buf.readBytes(bytes);
            if (!new String(bytes, StandardCharsets.UTF_16BE).equals("MC|PingHost")) {
                return;
            }

            // Not used
            buf.readShort();

            // The protocol version is present
            protocol = buf.readUnsignedByte();

            // There is extra host and port data
            if (protocol >= 73) {
                bytes = new byte[buf.readShort() << 1];
                buf.readBytes(bytes);

                final String host = new String(bytes, StandardCharsets.UTF_16BE);
                final int port = buf.readInt();

                virtualAddress = InetSocketAddress.createUnresolved(host, port);
            }

            readable = buf.readableBytes();
            if (readable > 0) {
                Lantern.getLogger().warn("Trailing bytes on a legacy ping message: {}b", readable);
            }
        }

        final MinecraftVersion clientVersion = Lantern.getGame().getMinecraftVersionCache()
                .getVersionOrUnknown(protocol, true);
        if (clientVersion == LanternMinecraftVersion.UNKNOWN) {
            Lantern.getLogger().debug("Client with unknown legacy protocol version {} pinged the server.",
                    protocol);
        }

        // The message was successfully decoded as a legacy one
        legacy = true;

        final MinecraftVersion serverVersion = Lantern.getGame().getPlatform().getMinecraftVersion();
        Text description = server.getMotd();

        final InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
        final LanternStatusClient client = new LanternStatusClient(address, clientVersion, virtualAddress);
        final ClientPingServerEvent.Response.Players players = LanternStatusHelper.createPlayers(server);
        final LanternStatusResponse response = new LanternStatusResponse(serverVersion, server.getFavicon(),
                description, players);

        final ClientPingServerEvent event = SpongeEventFactory
                .createClientPingServerEvent(Cause.source(client).build(), client, response);
        Sponge.getEventManager().post(event);

        // Cancelled, we are done here
        if (event.isCancelled()) {
            ctx.channel().close();
            return;
        }

        description = response.getDescription();
        int online = players.getOnline();
        final int max = players.getMax();

        // The players should be hidden, this will replace the player count
        // with ???
        if (!response.getPlayers().isPresent()) {
            online = -1;
        }

        final String data;

        if (full) {
            final String description0 = getFirstLine(
                    TextSerializers.LEGACY_FORMATTING_CODE.serialize(description));
            // 1. This value is always 1.
            // 2. The protocol version, just use a value out of range
            //    of the available ones.
            // 3. The version/name string of the server.
            // 4. The motd of the server. In legacy format.
            // 5. The online players
            // 6. The maximum amount of players
            data = String.format("\u00A7%s\u0000%s\u0000%s\u0000%s\u0000%s\u0000%s", 1, 127,
                    response.getVersion().getName(), description0, online, max);
        } else {
            final String description0 = getFirstLine(TextSerializers.PLAIN.serialize(description));
            // 1. The motd of the server. In legacy format.
            // 2. The online players
            // 3. The maximum amount of players
            data = String.format("%s\u00A7%s\u00A7%s", description0, online, max);
        }

        sendDisconnectMessage(ctx, data);
    } catch (Exception ignore) {
    } finally {
        if (legacy) {
            buf.release();
        } else {
            buf.resetReaderIndex();
            ctx.channel().pipeline().remove(this);
            ctx.fireChannelRead(buf);
        }
    }
}

From source file:org.legacy.network.protocol.handshake.HandshakeDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    if (buffer.isReadable()) {
        if (ctx.pipeline().get(HandshakeDecoder.class) != null) {
            ctx.pipeline().remove(this);
        }/*from  w  w w . j av a2 s .c o  m*/
        int opcode = buffer.readUnsignedByte() & 0xFF;
        switch (opcode) {
        case 15:
            int size = buffer.readUnsignedByte();
            if (buffer.readableBytes() < size) {
                ctx.channel().close();
                return;
            }
            int major_version = buffer.readInt();
            int minor_version = buffer.readInt();
            if (major_version != Framework.MAJOR_VERSION || minor_version != Framework.MINOR_VERSION) {
                buffer.writeByte(6);
                ctx.channel().close();
                return;
            }
            String ondemand_token = BufferUtils.readBufferedString(buffer);
            if (!ondemand_token.equals(Framework.ONDEMAND_SESSION_TOKEN)) {
                ctx.channel().close();
                return;
            }
            ByteBuf buf = Unpooled.buffer();
            buf.writeByte(0);
            for (int element : Framework.CRC_UPDATE_KEYS) {
                buf.writeInt(element);
            }
            ctx.channel().write(buf);
            ctx.pipeline().addBefore("channel-handler", "decoder", new OnDemandDecoder());
            break;
        default:
            LegacyLogger.fireWarnMessage(this, "Unknown Handshake Opcode: " + opcode);
        }
    }
}

From source file:org.legacy.network.protocol.ondemand.OnDemandDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    if (buffer.readableBytes() < 6)
        return;//from w  ww  . j  a va2  s.  com

    int opcode = buffer.readUnsignedByte();
    if (opcode == 0 || opcode == 1) {
        int type = buffer.readUnsignedByte();
        int file = buffer.readInt();
        out.add(new OnDemandRequestMessage(opcode == 1, type, file));
    } else if (opcode == 4) {
        int key = buffer.readUnsignedByte();
        buffer.readerIndex(buffer.readerIndex() + 2);
        out.add(new OnDemandEncryptionMessage(key));
    } else {
        buffer.readerIndex(buffer.readerIndex() + 5);
        return;
    }
}