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:net.ieldor.utility.flooder.FlooderChannelHandler.java

License:Open Source License

@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf buf) throws IOException {
    Channel channel = ctx.channel();

    if (state == State.READ_SERVER_SESSION_KEY) {
        if (buf.readableBytes() >= 9) {
            if (buf.readUnsignedByte() != 0)
                throw new IOException("expecting EXCHANGE_KEYS opcode");

            serverSessionKey = buf.readLong();

            ByteBuf payload = Unpooled.buffer();
            payload.writeInt(530);//from  w  w  w  .java 2  s . com

            payload.writeByte(0);
            payload.writeByte(0);
            payload.writeByte(0);

            payload.writeByte(0);
            payload.writeShort(765);
            payload.writeShort(503);

            payload.writeByte(0);

            for (int i = 0; i < 24; i++)
                payload.writeByte(0);

            ByteBufUtils.writeString(payload, "kKmok3kJqOeN6D3mDdihco3oPeYN2KFy6W5--vZUbNA");

            payload.writeInt(0);
            payload.writeInt(0);
            payload.writeShort(0);

            for (int i = 0; i < 28; i++) {
                payload.writeInt(crc[i]);
            }

            payload.writeByte(10);
            payload.writeLong(clientSessionKey);
            payload.writeLong(serverSessionKey);
            payload.writeLong(encodedUsername);
            ByteBufUtils.writeString(payload, password);

            ByteBuf packet = Unpooled.buffer();
            packet.writeByte(18);
            packet.writeShort(payload.readableBytes());
            packet.writeBytes(payload);

            channel.write(packet);

            int[] seed = new int[4];
            seed[0] = (int) (clientSessionKey >> 32);
            seed[1] = (int) clientSessionKey;
            seed[2] = (int) (serverSessionKey >> 32);
            seed[3] = (int) serverSessionKey;

            state = State.READ_LOGIN_STATUS;
        }
    }

    if (state == State.READ_LOGIN_STATUS) {
        if (buf.readable()) {
            int status = buf.readUnsignedByte();
            if (status != 2)
                throw new IOException("expecting OK login response");

            state = State.READ_LOGIN_PAYLOAD;
        }
    }

    if (state == State.READ_LOGIN_PAYLOAD) {
        if (buf.readableBytes() >= 11) {
            buf.readerIndex(buf.readerIndex() + 11);

            state = State.READ_GAME_OPCODE;
        }
    }

    if (state == State.READ_GAME_OPCODE) {

    }
}

From source file:net.minecrell.quartz.mixin.network.MixinLegacyPingHandler.java

License:MIT License

private boolean readLegacy(ChannelHandlerContext ctx, ByteBuf buf) {
    if (buf.readUnsignedByte() != 0xFE) {
        return false;
    }//from   w  w w .j a va2  s.c om

    MinecraftServer server = this.system.getServer();
    InetSocketAddress client = (InetSocketAddress) ctx.channel().remoteAddress();
    ServerStatusResponse response;

    int i = buf.readableBytes();
    switch (i) {
    case 0:
        logger.debug("Ping: (<=1.3) from {}:{}", client.getAddress(), client.getPort());

        response = QuartzStatusResponse.postLegacy(server, client, QuartzLegacyMinecraftVersion.V1_3, null);
        if (response != null) {
            this.writeResponse(ctx,
                    String.format("%s%d%d", QuartzStatusResponse.getUnformattedMotd(response),
                            response.getPlayers().getOnline(), response.getPlayers().getMax()));
        } else {
            ctx.close();
        }

        break;
    case 1:
        if (buf.readUnsignedByte() != 0x01) {
            return false;
        }

        logger.debug("Ping: (1.4-1.5) from {}:{}", client.getAddress(), client.getPort());

        response = QuartzStatusResponse.postLegacy(server, client, QuartzLegacyMinecraftVersion.V1_5, null);
        if (response != null) {
            this.writeResponse(ctx,
                    String.format("1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
                            response.getVersion().getProtocol(), response.getVersion().getName(),
                            QuartzStatusResponse.getMotd(response), response.getPlayers().getOnline(),
                            response.getPlayers().getMax()));
        } else {
            ctx.close();
        }

        break;
    default:
        if (buf.readUnsignedByte() != 0x01 || buf.readUnsignedByte() != 0xFA) {
            return false;
        }
        if (!buf.isReadable(2)) {
            break;
        }
        short length = buf.readShort();
        if (!buf.isReadable(length * 2)) {
            break;
        }
        if (!buf.readBytes(length * 2).toString(Charsets.UTF_16BE).equals("MC|PingHost")) {
            return false;
        }
        if (!buf.isReadable(2)) {
            break;
        }
        length = buf.readShort();
        if (!buf.isReadable(length)) {
            break;
        }

        int protocol = buf.readUnsignedByte();
        length = buf.readShort();
        String host = buf.readBytes(length * 2).toString(Charsets.UTF_16BE);
        int port = buf.readInt();

        logger.debug("Ping: (1.6) from {}:{}", client.getAddress(), client.getPort());

        response = QuartzStatusResponse.postLegacy(server, client,
                new QuartzLegacyMinecraftVersion(QuartzLegacyMinecraftVersion.V1_6, protocol),
                InetSocketAddress.createUnresolved(host, port));
        if (response != null) {
            this.writeResponse(ctx,
                    String.format("1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
                            response.getVersion().getProtocol(), response.getVersion().getName(),
                            QuartzStatusResponse.getMotd(response), response.getPlayers().getOnline(),
                            response.getPlayers().getMax()));
        } else {
            ctx.close();
        }

        break;
    }

    return true;
}

From source file:net.tomp2p.message.MessageHeaderCodec.java

License:Apache License

/**
 * Decodes a message object.//from  w  w  w.  j  a  va2  s.  c om
 * 
 * The format looks as follows: 28bit p2p version - 4bit message type - 32bit message id - 8bit message command - 160bit
 * sender id - 16bit sender tcp port - 16bit sender udp port - 160bit recipient id - 32bit content types - 8bit options. It total,
 * the header is of size 58 bytes.
 * 
 * @param buffer
 *            The buffer to decode from
 * @param recipientSocket
 *            The recipient of the message
 * @param senderSocket
 *            The sender of the packet, which has been set in the socket class
 * @return The partial message where only the header fields are set
 */
public static Message decodeHeader(final ByteBuf buffer, final InetSocketAddress recipientSocket,
        final InetSocketAddress senderSocket) {
    LOG.debug("Decode message. Recipient: {}, Sender:{}.", recipientSocket, senderSocket);
    final Message message = new Message();
    final int versionAndType = buffer.readInt();
    message.version(versionAndType >>> 4);
    message.type(Type.values()[(versionAndType & Utils.MASK_0F)]);
    message.messageId(buffer.readInt());
    final int command = buffer.readUnsignedByte();
    message.command((byte) command);
    final Number160 senderID = readID(buffer);
    final int tcpPort = buffer.readUnsignedShort();
    final int udpPort = buffer.readUnsignedShort();
    final Number160 recipientID = readID(buffer);
    message.recipient(new PeerAddress(recipientID, recipientSocket));
    final int contentTypes = buffer.readInt();
    message.hasContent(contentTypes != 0);
    message.contentTypes(decodeContentTypes(contentTypes, message));
    // set the address as we see it, important for port forwarding
    // identification
    final int options = buffer.readUnsignedByte();
    // three bits for the message options, 5 bits for the sender options
    message.options(options & 0x7);
    final int senderOptions = options >>> 3;
    final PeerAddress peerAddress = new PeerAddress(senderID, senderSocket.getAddress(), tcpPort, udpPort,
            senderOptions);
    message.sender(peerAddress);
    message.senderSocket(senderSocket);
    message.recipientSocket(recipientSocket);
    return message;
}

From source file:net.tomp2p.peers.PeerAddress.java

License:Apache License

/**
 * Creates a PeerAddress from a Netty ByteBuf.
 * //  w  ww. j a v  a2  s.c o m
 * @param channelBuffer
 *            The channel buffer to read from
 */
public PeerAddress(final ByteBuf channelBuffer) {
    // get the peer ID, this is independent of the type

    int readerIndex = channelBuffer.readerIndex();
    // get the type
    final int options = channelBuffer.readUnsignedByte();
    this.net6 = (options & NET6) > 0;
    this.firewalledUDP = (options & FIREWALL_UDP) > 0;
    this.firewalledTCP = (options & FIREWALL_TCP) > 0;
    this.relayed = (options & RELAYED) > 0;
    this.slow = (options & SLOW) > 0;
    this.portForwarding = (options & PORT_FORWARDING) > 0;
    final int relays = channelBuffer.readUnsignedByte();
    // first: three bits are the size 1,2,4
    // 000 means no relays
    // 001 means 1 relay
    // 010 means 2 relays
    // 011 means 3 relays
    // 100 means 4 relays
    // 101 means 5 relays
    // 110 is not used
    // 111 is not used
    // second: five bits indicate if IPv6 or IPv4 -> in total we can save 5 addresses
    this.relaySize = (relays >>> TYPE_BIT_SIZE) & MASK_07;
    final byte b = (byte) (relays & MASK_1F);
    this.relayType = Utils.createBitSet(b);
    // now comes the ID
    byte[] me = new byte[Number160.BYTE_ARRAY_SIZE];
    channelBuffer.readBytes(me);
    this.peerId = new Number160(me);

    this.peerSocketAddress = PeerSocketAddress.create(channelBuffer, isIPv4());

    if (relaySize > 0) {
        this.peerSocketAddresses = new ArrayList<PeerSocketAddress>(relaySize);
        for (int i = 0; i < relaySize; i++) {
            this.peerSocketAddresses.add(PeerSocketAddress.create(channelBuffer, !relayType.get(i)));
        }
    } else {
        this.peerSocketAddresses = EMPTY_PEER_SOCKET_ADDRESSES;
    }

    this.size = channelBuffer.readerIndex() - readerIndex;
    // not used here
    this.offset = -1;
    this.hashCode = peerId.hashCode();
}

From source file:net.tridentsdk.packets.play.in.PacketPlayInClientSettings.java

License:Open Source License

@Override
public Packet decode(ByteBuf buf) {
    this.locale = Locale.forLanguageTag(Codec.readString(buf));
    this.viewDistance = (short) buf.readByte();
    this.chatFlags = buf.readByte();
    this.chatColors = buf.readBoolean();

    this.skinParts = (byte) buf.readUnsignedByte();

    return this;
}

From source file:net.tridentsdk.packets.play.in.PacketPlayInClientStatus.java

License:Open Source License

@Override
public Packet decode(ByteBuf buf) {
    this.actionId = buf.readUnsignedByte();

    return this;
}

From source file:net.tridentsdk.packets.play.in.PacketPlayInEntityAction.java

License:Open Source License

@Override
public Packet decode(ByteBuf buf) {
    Codec.readVarInt32(buf); // ignore entity id as its the player's
    this.type = ActionType.getAction((int) buf.readUnsignedByte());
    this.jumpBoost = Codec.readVarInt32(buf);

    return this;
}

From source file:net.tridentsdk.packets.play.in.PacketPlayInSteerVehicle.java

License:Open Source License

@Override
public Packet decode(ByteBuf buf) {
    this.sideways = buf.readFloat();
    this.forward = buf.readFloat();
    this.flags = buf.readUnsignedByte();

    return this;
}

From source file:net.tridentsdk.server.packets.play.in.PacketPlayInEntityAction.java

License:Apache License

@Override
public Packet decode(ByteBuf buf) {
    Codec.readVarInt32(buf); // ignore entity id as its the player's
    this.type = ActionType.action((int) buf.readUnsignedByte());
    this.jumpBoost = Codec.readVarInt32(buf);

    return this;
}

From source file:nl.matsv.viabackwards.protocol.protocol1_9_4to1_10.chunks.ChunkSection1_10.java

License:Open Source License

/**
 * Read blocks from input stream./*from   www .  j a v  a  2s  .c  o m*/
 * This reads all the block related data:
 * <ul>
 * <li>Block length/palette type</li>
 * <li>Palette</li>
 * <li>Block hashes/palette reference</li>
 * </ul>
 *
 * @param input The buffer to read from.
 * @throws Exception
 */
public void readBlocks(ByteBuf input) throws Exception {
    palette.clear();

    // Reaad bits per block
    int bitsPerBlock = input.readUnsignedByte();
    long maxEntryValue = (1L << bitsPerBlock) - 1;

    if (bitsPerBlock == 0) {
        bitsPerBlock = 13;
    }
    if (bitsPerBlock < 4) {
        bitsPerBlock = 4;
    }
    if (bitsPerBlock > 8) {
        bitsPerBlock = 13;
    }
    int paletteLength = Type.VAR_INT.read(input);
    // Read palette
    for (int i = 0; i < paletteLength; i++) {
        if (bitsPerBlock != 13) {
            palette.add(Type.VAR_INT.read(input));
        } else {
            Type.VAR_INT.read(input);
        }
    }

    // Read blocks
    Long[] blockData = Type.LONG_ARRAY.read(input);
    if (blockData.length > 0) {
        for (int i = 0; i < blocks.length; i++) {
            int bitIndex = i * bitsPerBlock;
            int startIndex = bitIndex / 64;
            int endIndex = ((i + 1) * bitsPerBlock - 1) / 64;
            int startBitSubIndex = bitIndex % 64;
            int val;
            if (startIndex == endIndex) {
                val = (int) (blockData[startIndex] >>> startBitSubIndex & maxEntryValue);
            } else {
                int endBitSubIndex = 64 - startBitSubIndex;
                val = (int) ((blockData[startIndex] >>> startBitSubIndex
                        | blockData[endIndex] << endBitSubIndex) & maxEntryValue);
            }

            if (bitsPerBlock == 13) {
                int type = val >> 4;
                int data = val & 0xF;

                setBlock(i, type, data);
            } else {
                blocks[i] = val;
            }
        }
    }
}