Example usage for io.netty.buffer ByteBuf isReadable

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

Introduction

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

Prototype

public abstract boolean isReadable(int size);

Source Link

Document

Returns true if and only if this buffer contains equal to or more than the specified number of elements.

Usage

From source file:com.heliosapm.streams.metrics.StreamedMetricValue.java

License:Apache License

/**
 * Reads a streamed metric from the passed buffer
 * @param buff the buffer to read the streamed metric from
 * @return the appropriate type of StreamedMetric
 *///from  w  w  w.j  av a  2 s  .  com
public static StreamedMetricValue[] readAll(final ByteBuf buff) {
    final Set<StreamedMetricValue> metrics = new HashSet<StreamedMetricValue>();
    while (buff.isReadable(MIN_READABLE_BYTES)) {
        metrics.add(read(buff).forValue(1L));
    }
    return metrics.toArray(new StreamedMetricValue[metrics.size()]);
}

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;
    }// ww  w .j  a v  a 2 s . c  o m

    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:org.apache.activemq.artemis.utils.AbstractByteBufPool.java

License:Apache License

/**
 * Returns a pooled entry if possible, a new one otherwise.
 * <p>//w  w  w  .  j a  v  a 2s  .c o m
 * The {@code byteBuf}'s {@link ByteBuf#readerIndex()} is incremented by {@code length} after it.
 */
public final T getOrCreate(final ByteBuf byteBuf) {
    final int length = byteBuf.readInt();
    if (!canPool(byteBuf, length)) {
        return create(byteBuf, length);
    } else {
        if (!byteBuf.isReadable(length)) {
            throw new IndexOutOfBoundsException();
        }
        final int bytesOffset = byteBuf.readerIndex();
        final int hashCode = hashCode(byteBuf, bytesOffset, length);
        //fast % operation with power of 2 entries.length
        final int firstIndex = hashCode & mask;
        final T firstEntry = entries[firstIndex];
        if (isEqual(firstEntry, byteBuf, bytesOffset, length)) {
            byteBuf.skipBytes(length);
            return firstEntry;
        }
        final int secondIndex = (hashCode >> shift) & mask;
        final T secondEntry = entries[secondIndex];
        if (isEqual(secondEntry, byteBuf, bytesOffset, length)) {
            byteBuf.skipBytes(length);
            return secondEntry;
        }
        final T internedEntry = create(byteBuf, length);
        final int entryIndex = firstEntry == null ? firstIndex : secondIndex;
        entries[entryIndex] = internedEntry;
        return internedEntry;
    }
}

From source file:org.ethereum.net.rlpx.HandshakeHandler.java

License:Open Source License

private void decodeHandshake(final ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {

    if (handshake.isInitiator()) {
        if (frameCodec == null) {

            byte[] responsePacket = new byte[AuthResponseMessage.getLength() + ECIESCoder.getOverhead()];
            if (!buffer.isReadable(responsePacket.length))
                return;
            buffer.readBytes(responsePacket);

            try {

                // trying to decode as pre-EIP-8

                AuthResponseMessage response = handshake.handleAuthResponse(myKey, initiatePacket,
                        responsePacket);
                loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), response);

            } catch (Throwable t) {

                // it must be format defined by EIP-8 then

                responsePacket = readEIP8Packet(buffer, responsePacket);

                if (responsePacket == null)
                    return;

                AuthResponseMessageV4 response = handshake.handleAuthResponseV4(myKey, initiatePacket,
                        responsePacket);
                loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), response);
            }/*w  w  w  . java  2s. co  m*/

            EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
            this.frameCodec = new FrameCodec(secrets);

            loggerNet.debug("auth exchange done");
            channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId));
        } else {
            loggerWire.info("MessageCodec: Buffer bytes: " + buffer.readableBytes());
            List<Frame> frames = frameCodec.readFrames(buffer);
            if (frames == null || frames.isEmpty())
                return;
            Frame frame = frames.get(0);
            byte[] payload = ByteStreams.toByteArray(frame.getStream());
            if (frame.getType() == P2pMessageCodes.HELLO.asByte()) {
                HelloMessage helloMessage = new HelloMessage(payload);
                if (loggerNet.isDebugEnabled())
                    loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), helloMessage);
                isHandshakeDone = true;
                this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, helloMessage);
            } else {
                DisconnectMessage message = new DisconnectMessage(payload);
                if (loggerNet.isDebugEnabled())
                    loggerNet.debug("From: {}    Recv:  {}", channel, message);
                channel.getNodeStatistics().nodeDisconnectedRemote(message.getReason());
            }
        }
    } else {
        loggerWire.debug("Not initiator.");
        if (frameCodec == null) {
            loggerWire.debug("FrameCodec == null");
            byte[] authInitPacket = new byte[AuthInitiateMessage.getLength() + ECIESCoder.getOverhead()];
            if (!buffer.isReadable(authInitPacket.length))
                return;
            buffer.readBytes(authInitPacket);

            this.handshake = new EncryptionHandshake();

            byte[] responsePacket;

            try {

                // trying to decode as pre-EIP-8
                AuthInitiateMessage initiateMessage = handshake.decryptAuthInitiate(authInitPacket, myKey);
                loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), initiateMessage);

                AuthResponseMessage response = handshake.makeAuthInitiate(initiateMessage, myKey);
                loggerNet.debug("To:   {}    Send:  {}", ctx.channel().remoteAddress(), response);
                responsePacket = handshake.encryptAuthResponse(response);

            } catch (Throwable t) {

                // it must be format defined by EIP-8 then
                try {

                    authInitPacket = readEIP8Packet(buffer, authInitPacket);

                    if (authInitPacket == null)
                        return;

                    AuthInitiateMessageV4 initiateMessage = handshake.decryptAuthInitiateV4(authInitPacket,
                            myKey);
                    loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), initiateMessage);

                    AuthResponseMessageV4 response = handshake.makeAuthInitiateV4(initiateMessage, myKey);
                    loggerNet.debug("To:   {}    Send:  {}", ctx.channel().remoteAddress(), response);
                    responsePacket = handshake.encryptAuthResponseV4(response);

                } catch (InvalidCipherTextException ce) {
                    loggerNet.warn("Can't decrypt AuthInitiateMessage from " + ctx.channel().remoteAddress()
                            + ". Most likely the remote peer used wrong public key (NodeID) to encrypt message.");
                    return;
                }
            }

            handshake.agreeSecret(authInitPacket, responsePacket);

            EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
            this.frameCodec = new FrameCodec(secrets);

            ECPoint remotePubKey = this.handshake.getRemotePublicKey();

            byte[] compressed = remotePubKey.getEncoded();

            this.remoteId = new byte[compressed.length - 1];
            System.arraycopy(compressed, 1, this.remoteId, 0, this.remoteId.length);

            final ByteBuf byteBufMsg = ctx.alloc().buffer(responsePacket.length);
            byteBufMsg.writeBytes(responsePacket);
            ctx.writeAndFlush(byteBufMsg).sync();
        } else {
            List<Frame> frames = frameCodec.readFrames(buffer);
            if (frames == null || frames.isEmpty())
                return;
            Frame frame = frames.get(0);

            Message message = new P2pMessageFactory().create((byte) frame.getType(),
                    ByteStreams.toByteArray(frame.getStream()));
            loggerNet.debug("From: {}    Recv:  {}", ctx.channel().remoteAddress(), message);

            if (frame.getType() == P2pMessageCodes.DISCONNECT.asByte()) {
                loggerNet.debug("Active remote peer disconnected right after handshake.");
                return;
            }

            if (frame.getType() != P2pMessageCodes.HELLO.asByte()) {
                throw new RuntimeException("The message type is not HELLO or DISCONNECT: " + message);
            }

            final HelloMessage inboundHelloMessage = (HelloMessage) message;

            // now we know both remote nodeId and port
            // let's set node, that will cause registering node in NodeManager
            channel.initWithNode(remoteId, inboundHelloMessage.getListenPort());

            // Secret authentication finish here
            channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId));
            isHandshakeDone = true;
            this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, inboundHelloMessage);
            channel.getNodeStatistics().rlpxInHello.add();
        }
    }
}

From source file:org.ethereum.net.rlpx.HandshakeHandler.java

License:Open Source License

private byte[] readEIP8Packet(ByteBuf buffer, byte[] plainPacket) {

    int size = bigEndianToShort(plainPacket);
    if (size < plainPacket.length)
        throw new IllegalArgumentException("AuthResponse packet size is too low");

    int bytesLeft = size - plainPacket.length + 2;
    byte[] restBytes = new byte[bytesLeft];

    if (!buffer.isReadable(restBytes.length))
        return null;

    buffer.readBytes(restBytes);/*  w w  w.j a  v  a 2s  .c o m*/

    byte[] fullResponse = new byte[size + 2];
    System.arraycopy(plainPacket, 0, fullResponse, 0, plainPacket.length);
    System.arraycopy(restBytes, 0, fullResponse, plainPacket.length, restBytes.length);

    return fullResponse;
}

From source file:org.iotivity.cloud.base.protocols.coap.CoapDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    // TODO: need exceptional case handling
    while (in.isReadable(bufferToRead)) {

        switch (nextState) {
        case SHIM_HEADER:
            int shimHeader = in.readByte();
            bufferToRead = (shimHeader >>> 4) & 0x0F;
            tokenLength = (shimHeader) & 0x0F;
            switch (bufferToRead) {
            case 13:
                bufferToRead = 1;//  w  w  w .j  ava  2  s. c  o m
                nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
                break;
            case 14:
                bufferToRead = 2;
                nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
                break;
            case 15:
                bufferToRead = 4;
                nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
                break;
            default:
                optionPayloadLength = bufferToRead;
                bufferToRead += 1 + tokenLength; // code + tkl
                nextState = ParsingState.CODE_TOKEN_OPTION;
                break;
            }
            break;

        case OPTION_PAYLOAD_LENGTH:
            switch (bufferToRead) {
            case 1:
                optionPayloadLength = 13 + (in.readByte() & 0xFF);
                break;

            case 2:
                optionPayloadLength = 269 + (((in.readByte() & 0xFF) << 8) + (in.readByte() & 0xFF));
                break;

            case 4:
                optionPayloadLength = 65805 + (((in.readByte() & 0xFF) << 24) + ((in.readByte() & 0xFF) << 16)
                        + ((in.readByte() & 0xFF) << 8) + (in.readByte() & 0xFF));
                break;
            }
            nextState = ParsingState.CODE_TOKEN_OPTION;
            bufferToRead = 1 + tokenLength + optionPayloadLength; // code
                                                                  // +
                                                                  // tkl
            break;

        case CODE_TOKEN_OPTION:
            int code = in.readByte() & 0xFF;

            if (code <= 31) {
                partialMsg = new CoapRequest(code);
            } else {
                partialMsg = new CoapResponse(code);
            }

            if (tokenLength > 0) {
                byte[] token = new byte[tokenLength];
                in.readBytes(token);
                partialMsg.setToken(token);
            }

            if (optionPayloadLength > 0) {
                int optionLen = parseOptions(partialMsg, in, optionPayloadLength);
                if (optionPayloadLength > optionLen) {
                    nextState = ParsingState.PAYLOAD;
                    bufferToRead = optionPayloadLength - optionLen;
                    continue;
                }
            }

            nextState = ParsingState.FINISH;
            bufferToRead = 0;

            break;

        case PAYLOAD:
            byte[] payload = new byte[bufferToRead];
            in.readBytes(payload);
            partialMsg.setPayload(payload);
            nextState = ParsingState.FINISH;
            bufferToRead = 0;
            break;

        case FINISH:
            nextState = ParsingState.SHIM_HEADER;
            bufferToRead = 1;
            out.add(partialMsg);
            break;

        default:
            break;
        }
    }

    in.discardReadBytes();
}

From source file:org.jfxvnc.net.rfb.codec.decoder.BellDecoder.java

License:Apache License

@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable(1)) {
        return false;
    }//from ww  w . java  2s.  c  om
    in.skipBytes(1);
    out.add(new BellEvent());
    return true;
}

From source file:org.jfxvnc.net.rfb.codec.decoder.ColourMapEntriesDecoder.java

License:Apache License

@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    if (colorBuf == null) {
        if (!in.isReadable(12)) {
            return false;
        }//from w w w  .j  av a  2  s.  co  m
        in.skipBytes(2);
        firstColor = in.readUnsignedShort();
        numberOfColor = in.readUnsignedShort();
        int size = numberOfColor - firstColor;
        colorBuf = Unpooled.buffer(size * 6, size * 6);
    }
    colorBuf.writeBytes(in);

    if (!colorBuf.isWritable()) {
        return out.add(new ColourMapEntriesEvent(firstColor, numberOfColor, colorBuf));
    }
    return false;
}

From source file:org.jfxvnc.net.rfb.codec.decoder.FramebufferUpdateRectDecoder.java

License:Apache License

private boolean readRect(ChannelHandlerContext ctx, ByteBuf m, List<Object> out) {
    if (!m.isReadable(12)) {
        return false;
    }//from  ww w . j a  va 2s . c om
    int x = m.readUnsignedShort();
    int y = m.readUnsignedShort();
    int w = m.readUnsignedShort();
    int h = m.readUnsignedShort();
    int enc = m.readInt();

    rect = new FrameRect(x, y, w, h, Encoding.valueOf(enc));
    currentRect++;
    logger.debug("{}of{} - ({}) {}", currentRect, numberRects, rect, enc);

    if (w == 0 || h == 0) {
        if (currentRect == numberRects) {
            state = State.INIT;
            ctx.pipeline().fireUserEventTriggered(ProtocolState.FBU_REQUEST);
            return true;
        }
        return false;
    }
    return true;
}

From source file:org.jfxvnc.net.rfb.codec.decoder.ProtocolVersionDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable(length)) {
        return;/*  w w w . j  ava 2  s .com*/
    }
    byte[] rfb = new byte[length];
    in.readBytes(rfb);
    String rfbVersion = new String(rfb, ASCII);
    out.add(new ProtocolVersion(rfbVersion));
    ctx.pipeline().remove(this);
}