Example usage for io.netty.buffer ByteBuf markReaderIndex

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

Introduction

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

Prototype

public abstract ByteBuf markReaderIndex();

Source Link

Document

Marks the current readerIndex in 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   w ww .  j av  a 2s  .  co m*/
 * 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();

        try {//from  w w  w .j  a v  a 2 s.c o  m

            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.netlibs.bgp.netty.protocol.open.CapabilityCodec.java

License:Apache License

public static Capability decodeCapability(final ByteBuf buffer) {
    Capability cap = null;/*from  w  w w  .  j ava2s  .co  m*/

    try {
        buffer.markReaderIndex();

        final int type = buffer.readUnsignedByte();

        switch (type) {
        case BGPv4Constants.BGP_CAPABILITY_TYPE_MULTIPROTOCOL:
            cap = decodeMultiProtocolCapability(buffer);
            break;
        case BGPv4Constants.BGP_CAPABILITY_TYPE_ROUTE_REFRESH:
            cap = decodeRouteRefreshCapability(buffer);
            break;
        case BGPv4Constants.BGP_CAPABILITY_TYPE_AS4_NUMBERS:
            cap = decodeAutonomousSystem4Capability(buffer);
            break;
        case BGPv4Constants.BGP_CAPABILITY_TYPE_OUTBOUND_ROUTE_FILTERING:
            cap = decodeOutboundRouteFilteringCapability(buffer);
            break;
        default:
            cap = decodeUnknownCapability(type, buffer);
            break;
        }
    } catch (final CapabilityException e) {
        buffer.resetReaderIndex();

        final int type = buffer.readUnsignedByte();
        final int capLength = buffer.readUnsignedByte();

        final byte[] capPacket = new byte[capLength + 2];

        buffer.readBytes(capPacket, 2, capLength);
        capPacket[0] = (byte) type;
        capPacket[1] = (byte) capLength;

        e.setCapability(capPacket);
        throw e;
    }

    return cap;
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

/**
 * Adapted from {@link DefaultDnsRecordDecoder#decodeName(ByteBuf)}.
 *///from  w w  w .  jav  a 2s .  c  o m
static String decodeDomainName(ByteBuf in) {
    in.markReaderIndex();
    try {
        return decodeName(in);
    } catch (CorruptedFrameException e) {
        // In this case we just return null.
        return null;
    } finally {
        in.resetReaderIndex();
    }
}

From source file:me.bigteddy98.mcproxy.MainTest.java

License:Open Source License

private static void print(String name, ByteBuf buf) {
    buf.markReaderIndex();
    byte[] array = new byte[buf.readableBytes()];
    buf.readBytes(array, 0, buf.readableBytes());
    ProxyLogger.debug("Current bytes: " + getHexString(array));
    buf.resetReaderIndex();/*from w w  w  .j av  a2 s.  c  o  m*/
}

From source file:me.bigteddy98.mcproxy.protocol.BufferUtils.java

License:Open Source License

public static void printBufferHex(String name, ByteBuf buf) {
    buf.markReaderIndex();
    byte[] array = new byte[buf.readableBytes()];
    buf.readBytes(array, 0, buf.readableBytes());
    ProxyLogger.debug("Buffer hex data for name " + name + " " + getHexString(array));
    buf.resetReaderIndex();/*from   w w  w .  j  a v a2 s.  c  om*/
}

From source file:me.bigteddy98.mcproxy.protocol.NetworkManager.java

License:Open Source License

public synchronized List<Packet> handleServerBoundPackets(ByteBuf originalBuffer, ByteBuf bufferClone)
        throws InstantiationException, IllegalAccessException {
    List<Packet> list = new ArrayList<>();
    if (bufferClone.readableBytes() == 0) {
        return list;
    }/*w  ww .  j a va  2  s  . co  m*/
    PacketDataWrapper wrapper = new PacketDataWrapper(bufferClone);
    while (bufferClone.readableBytes() > 0) {
        bufferClone.markReaderIndex();
        int readBytes = bufferClone.readableBytes();
        int length = 0;
        {
            int bytes = 0;
            byte in;
            while (true) {
                if (readBytes < 1) {
                    bufferClone.resetReaderIndex();
                    return list;
                }
                in = bufferClone.readByte();
                length |= (in & 0x7F) << (bytes++ * 7);
                if (bytes > 5) {
                    throw new RuntimeException("VarInt too big");
                }
                if ((in & 0x80) != 0x80) {
                    break;
                }
            }
        }
        if (bufferClone.readableBytes() < length) {
            bufferClone.resetReaderIndex();
            return list;
        }
        int id = wrapper.readVarInt();
        Class<? extends Packet> clazz = PacketRegistry.getServerBoundPacket(id, this.currentState);
        if (clazz == null) {
            return list;
        }
        Packet packet = clazz.newInstance();
        packet.read(wrapper);
        packet.onReceive(this, new PacketReceiveEvent());
        list.add(packet);
        ProxyLogger.debug("Handled " + packet.toString());
        bufferClone.discardSomeReadBytes();
    }
    return list;
}

From source file:me.bigteddy98.mcproxy.protocol.NetworkManager.java

License:Open Source License

public synchronized List<Packet> handleClientBoundPackets(ByteBuf originalBuffer, ByteBuf bufferClone)
        throws InstantiationException, IllegalAccessException {
    List<Packet> list = new ArrayList<>();
    if (bufferClone.readableBytes() == 0) {
        return list;
    }/*from w ww. j a va  2 s .  c  o  m*/
    PacketDataWrapper wrapper = new PacketDataWrapper(bufferClone);
    while (bufferClone.readableBytes() > 0) {
        bufferClone.markReaderIndex();
        int readBytes = bufferClone.readableBytes();
        int length = 0;
        {
            int bytes = 0;
            byte in;
            while (true) {
                if (readBytes < 1) {
                    bufferClone.resetReaderIndex();
                    return list;
                }
                in = bufferClone.readByte();
                length |= (in & 0x7F) << (bytes++ * 7);
                if (bytes > 5) {
                    throw new RuntimeException("VarInt too big");
                }
                if ((in & 0x80) != 0x80) {
                    break;
                }
            }
        }
        if (bufferClone.readableBytes() < length) {
            bufferClone.resetReaderIndex();
            return list;
        }
        int id = wrapper.readVarInt();
        Class<? extends Packet> clazz = PacketRegistry.getClientBoundPacket(id, this.currentState);
        if (clazz == null) {
            return list;
        }
        Packet packet = clazz.newInstance();
        packet.read(wrapper);
        packet.onReceive(this, new PacketReceiveEvent());
        list.add(packet);
        ProxyLogger.debug("Handled " + packet.toString());
        bufferClone.discardSomeReadBytes();
    }
    return list;
}

From source file:me.bigteddy98.slimeportal.MainTest.java

License:Open Source License

private static void print(String name, ByteBuf buf) {
    buf.markReaderIndex();
    byte[] array = new byte[buf.readableBytes()];
    buf.readBytes(array, 0, buf.readableBytes());
    SlimeLogger.debug("Current bytes: " + getHexString(array));
    buf.resetReaderIndex();//from w w  w.  j a  v  a  2 s .c om
}

From source file:me.bigteddy98.slimeportal.protocol.BufferUtils.java

License:Open Source License

public static void printBufferHex(String name, ByteBuf buf) {
    buf.markReaderIndex();
    byte[] array = new byte[buf.readableBytes()];
    buf.readBytes(array, 0, buf.readableBytes());
    SlimeLogger.debug("Buffer hex data for name " + name + " " + getHexString(array));
    buf.resetReaderIndex();//from w w  w  .  j  a  v a2s  . co m
}