Example usage for io.netty.buffer ByteBuf readerIndex

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

Introduction

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

Prototype

public abstract int readerIndex();

Source Link

Document

Returns the readerIndex of this buffer.

Usage

From source file:io.netlibs.bgp.handlers.BGPv4Reframer.java

License:Apache License

/**
 * reframe the received packet to completely contain the next BGPv4 packet. It peeks into the first four bytes of the TCP stream which
 * contain a 16-bit marker and a 16-bit length field. The marker must be all one's and the length value must be between 19 and 4096
 * according to RFC 4271. The marker and length constraints are verified and if either is violated the connection is closed early.
 * /*from ww  w .  j a  v a2 s.c  om*/
 * Any packets that are added start on the type byte. The buffer will contain the full message payload.
 * 
 */

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

    if (buffer.readableBytes() < (BGPv4Constants.BGP_PACKET_MIN_LENGTH - 1)) {
        // need more bytes for a full read.
        return;
    }

    buffer.markReaderIndex();

    // confirm that the next BGP_PACKET_MARKER_LENGTH bytes are all 0xff.

    if (buffer.forEachByte(buffer.readerIndex(), BGPv4Constants.BGP_PACKET_MARKER_LENGTH,
            value -> value == (byte) 0xff) != -1) {
        log.error("received invalid marker, closing connection");
        NotificationHelper.sendEncodedNotification(ctx, new ConnectionNotSynchronizedNotificationPacket(),
                new BgpEventFireChannelFutureListener(ctx));
        return;
    }

    // skip the marker.
    buffer.skipBytes(BGPv4Constants.BGP_PACKET_MARKER_LENGTH);

    // read the packet length.
    final int length = buffer.readUnsignedShort();

    if ((length < BGPv4Constants.BGP_PACKET_MIN_LENGTH) || (length > BGPv4Constants.BGP_PACKET_MAX_LENGTH)) {

        log.error("received illegal packet size {}, must be between {} and {}. closing connection",
                new Object[] { length, BGPv4Constants.BGP_PACKET_MIN_LENGTH,
                        BGPv4Constants.BGP_PACKET_MAX_LENGTH });

        NotificationHelper.sendEncodedNotification(ctx, new BadMessageLengthNotificationPacket(length),
                new BgpEventFireChannelFutureListener(ctx));

        return;

    }

    final int mustRead = (length - (BGPv4Constants.BGP_PACKET_MARKER_LENGTH + 2)); // we have consumed marker and length at this point

    // must if we don't have the right amount, abort.
    if (buffer.readableBytes() < mustRead) {
        buffer.resetReaderIndex();
        return;
    }

    out.add(buffer.readBytes(mustRead));

}

From source file:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java

License:Apache License

private List<PathAttribute> decodePathAttributes(final ByteBuf buffer) {

    final List<PathAttribute> attributes = new LinkedList<PathAttribute>();

    while (buffer.isReadable()) {

        buffer.markReaderIndex();//from   w w w.ja  v a2 s  . c o  m

        try {

            final int flagsType = buffer.readUnsignedShort();

            final boolean optional = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_OPTIONAL_BIT) != 0);
            final boolean transitive = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TRANSITIVE_BIT) != 0);
            final boolean partial = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_PARTIAL_BIT) != 0);
            final int typeCode = (flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MASK);

            int valueLength = 0;

            if ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_EXTENDED_LENGTH_BIT) != 0) {
                valueLength = buffer.readUnsignedShort();
            } else {
                valueLength = buffer.readUnsignedByte();
            }

            // final ByteBuf valueBuffer = Unpooled.buffer(valueLength);
            // buffer.readBytes(valueBuffer);

            final ByteBuf valueBuffer = buffer.readBytes(valueLength);

            PathAttribute attr = null;

            switch (typeCode) {
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AGGREGATOR:
                attr = this.decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_AGGREGATOR:
                attr = this.decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_PATH:
                attr = this.decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS_PATH:
                attr = this.decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ATOMIC_AGGREGATE:
                attr = this.decodeAtomicAggregatePathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_COMMUNITIES:
                attr = this.decodeCommunityPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_LOCAL_PREF:
                attr = this.decodeLocalPrefPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MULTI_EXIT_DISC:
                attr = this.decodeMultiExitDiscPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_NEXT_HOP:
                attr = this.decodeNextHopPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGIN:
                attr = this.decodeOriginPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_REACH_NLRI:
                attr = this.decodeMpReachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_UNREACH_NLRI:
                attr = this.decodeMpUnreachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGINATOR_ID:
                attr = this.decodeOriginatorIDPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_CLUSTER_LIST:
                attr = this.decodeClusterListPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_EXTENDED_COMMUNITIES:
                attr = this.decodeExtendedCommunityPathAttribute(valueBuffer);
                break;
            default: {
                final byte[] value = new byte[valueBuffer.readableBytes()];

                valueBuffer.readBytes(value);
                attr = new UnknownPathAttribute(typeCode, value);
            }
                break;
            }
            attr.setOptional(optional);
            attr.setTransitive(transitive);
            attr.setPartial(partial);

            attributes.add(attr);

        } catch (final AttributeException ex) {

            final int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            final int attributeLength = endReadIndex - buffer.readerIndex();
            final byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);
            ex.setOffendingAttribute(packet);

            throw ex;

        } catch (final IndexOutOfBoundsException ex) {

            // this is almost certinally an internal error with parsing ....

            final int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            final int attributeLength = endReadIndex - buffer.readerIndex();
            final byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);

            throw new AttributeLengthException(ex, packet);

        }

    }

    return attributes;
}

From source file:io.nodyn.buffer.Buffer.java

License:Apache License

public static byte[] extractByteArray(JSObject object) {
    ByteBuf buf = extract(object);
    byte[] bytes = new byte[bufLen(object)];
    buf.getBytes(buf.readerIndex(), bytes);
    return bytes;
}

From source file:io.nodyn.crypto.Hash.java

License:Apache License

public void update(ByteBuf buf) {
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);
    this.digest.update(bytes, 0, bytes.length);
}

From source file:io.nodyn.crypto.Hmac.java

License:Apache License

public void update(ByteBuf buf) {
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);
    this.hmac.update(bytes, 0, bytes.length);
}

From source file:io.nodyn.http.HTTPParser.java

License:Apache License

protected boolean readRequestLine() {
    ByteBuf line = readLine();
    if (line == null) {
        return false;
    }//from   w  w  w  .j a  v a  2  s . c om

    int space = line.indexOf(line.readerIndex(), line.readerIndex() + line.readableBytes(), (byte) ' ');
    if (space < 0) {
        setError(Error.INVALID_METHOD);
        return false;
    }

    int len = space - line.readerIndex();

    ByteBuf methodBuf = line.readSlice(len);

    String methodName = methodBuf.toString(UTF8);
    for (int i = 0; i < METHODS.length; ++i) {
        if (METHODS[i].equals(methodName)) {
            this.method = i;
            break;
        }
    }

    if (this.method == null) {
        setError(Error.INVALID_METHOD);
        return false;
    }

    if ("CONNECT".equals(methodName)) {
        this.upgrade = true;
    }

    // skip the space
    line.readByte();

    space = line.indexOf(line.readerIndex(), line.readerIndex() + line.readableBytes(), (byte) ' ');

    ByteBuf urlBuf = null;
    ByteBuf versionBuf = null;
    if (space < 0) {
        // HTTP/1.0
        urlBuf = line.readSlice(line.readableBytes());
    } else {
        len = space - line.readerIndex();
        urlBuf = line.readSlice(len);
        versionBuf = line.readSlice(line.readableBytes());
    }

    this.url = urlBuf.toString(UTF8).trim();

    if (versionBuf != null) {
        if (!readVersion(versionBuf)) {
            setError(Error.INVALID_VERSION);
            return false;
        }
    } else {
        this.versionMajor = 1;
        this.versionMinor = 0;
    }
    return true;
}

From source file:io.nodyn.http.HTTPParser.java

License:Apache License

protected boolean readStatusLine() {
    ByteBuf line = readLine();

    if (line == null) {
        return false;
    }/*from  w w w .  j  a  v a2  s .  c  o m*/

    int space = line.indexOf(line.readerIndex(), line.readerIndex() + line.readableBytes(), (byte) ' ');

    if (space < 0) {
        setError(Error.INVALID_VERSION);
        return false;
    }

    int len = space - line.readerIndex();

    ByteBuf versionBuf = line.readSlice(len);

    if (!readVersion(versionBuf)) {
        setError(Error.INVALID_VERSION);
        return false;
    }

    // skip space
    line.readByte();

    space = line.indexOf(line.readerIndex(), line.readerIndex() + line.readableBytes(), (byte) ' ');

    if (space < 0) {
        setError(Error.INVALID_STATUS);
        return false;
    }

    len = space - line.readerIndex();

    ByteBuf statusBuf = line.readSlice(len);

    int status = -1;

    try {
        status = Integer.parseInt(statusBuf.toString(UTF8));
    } catch (NumberFormatException e) {
        setError(Error.INVALID_STATUS);
        return false;
    }

    if (status > 999 || status < 100) {
        setError(Error.INVALID_STATUS);
        return false;
    }

    this.statusCode = status;

    // skip space
    line.readByte();

    ByteBuf messageBuf = line.readSlice(line.readableBytes());

    this.statusMessage = messageBuf.toString(UTF8).trim();

    return true;
}

From source file:io.nodyn.http.HTTPParser.java

License:Apache License

protected boolean readVersion(ByteBuf versionBuf) {
    int dotLoc = versionBuf.indexOf(versionBuf.readerIndex(),
            versionBuf.readerIndex() + versionBuf.readableBytes(), (byte) '.');
    if (dotLoc < 0) {
        return false;
    }//from  w ww . j av  a2s .c  o m

    char majorChar = (char) versionBuf.getByte(dotLoc - 1);
    char minorChar = (char) versionBuf.getByte(dotLoc + 1);
    try {
        this.versionMajor = Integer.parseInt("" + majorChar);
        this.versionMinor = Integer.parseInt("" + minorChar);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

From source file:io.nodyn.http.HTTPParser.java

License:Apache License

protected boolean readHeader(ByteBuf line, List<String> target, boolean analyze) {
    int colonLoc = line.indexOf(line.readerIndex(), line.readerIndex() + line.readableBytes(), (byte) ':');

    if (colonLoc < 0) {
        // maybe it's a continued header
        if (line.readableBytes() > 1) {
            char c = (char) line.getByte(0);
            if (c == ' ' || c == '\t') {
                // it IS a continued header value
                int lastIndex = this.headers.size() - 1;
                String val = this.headers.get(lastIndex);
                val = val + " " + line.toString(ASCII).trim();
                this.headers.set(lastIndex, val);
                return true;
            }/*w  w  w .ja  v a 2  s. co m*/
        }
        return false;
    }

    int len = colonLoc - line.readerIndex();
    ByteBuf keyBuf = line.readSlice(len);

    // skip colon
    line.readByte();

    ByteBuf valueBuf = line.readSlice(line.readableBytes());

    String key = keyBuf.toString(UTF8).trim();
    String value = valueBuf.toString(UTF8).trim();

    target.add(key);
    target.add(value);

    if (analyze) {
        return analyzeHeader(key.toLowerCase(), value);
    }

    return true;
}

From source file:io.reactiverse.pgclient.impl.codec.util.Util.java

License:Apache License

public static void writeCString(ByteBuf dst, ByteBuf buf) {
    // Important : won't not change data index
    dst.writeBytes(buf, buf.readerIndex(), buf.readableBytes());
    dst.writeByte(0);/*from  w w w.  j  ava 2 s. c om*/
}