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.advantageous.conekt.dns.impl.netty.DnsResponseDecoder.java

License:Open Source License

/**
 * Retrieves a domain name given a buffer containing a DNS packet. If the
 * name contains a pointer, the position of the buffer will be set to
 * directly after the pointer's index after the name has been read.
 *
 * @param buf the byte buffer containing the DNS packet
 * @return the domain name for an entry//from w w  w  .  ja v a  2  s  .  c om
 */
public static String readName(ByteBuf buf) {
    int position = -1;
    StringBuilder name = new StringBuilder();
    for (int len = buf.readUnsignedByte(); buf.isReadable() && len != 0; len = buf.readUnsignedByte()) {
        boolean pointer = (len & 0xc0) == 0xc0;
        if (pointer) {
            if (position == -1) {
                position = buf.readerIndex() + 1;
            }
            buf.readerIndex((len & 0x3f) << 8 | buf.readUnsignedByte());
        } else {
            name.append(buf.toString(buf.readerIndex(), len, CharsetUtil.UTF_8)).append(".");
            buf.skipBytes(len);
        }
    }
    if (position != -1) {
        buf.readerIndex(position);
    }
    if (name.length() == 0) {
        return null;
    }
    return name.substring(0, name.length() - 1);
}

From source file:io.advantageous.conekt.dns.impl.netty.DnsResponseDecoder.java

License:Open Source License

/**
 * Decodes a resource record, given a DNS packet in a byte buffer.
 *
 * @param buf the byte buffer containing the DNS packet
 * @return a {@link DnsResource} record containing response data
 *///from w  w  w  .j a  v a2  s  .co m
private static DnsResource decodeResource(ByteBuf buf, ByteBufAllocator allocator) {
    String name = readName(buf);
    int type = buf.readUnsignedShort();
    int aClass = buf.readUnsignedShort();
    long ttl = buf.readUnsignedInt();
    int len = buf.readUnsignedShort();
    ByteBuf resourceData = allocator.buffer(len);
    int contentIndex = buf.readerIndex();
    resourceData.writeBytes(buf, len);
    return new DnsResource(name, type, aClass, ttl, contentIndex, resourceData);
}

From source file:io.airlift.drift.transport.netty.codec.HeaderTransport.java

License:Apache License

public static Optional<FrameInfo> tryDecodeFrameInfo(ByteBuf input) {
    ByteBuf buffer = input.retainedDuplicate();
    try {/*w w  w.  j a  v  a  2s . c o  m*/
        if (buffer.readableBytes() < FRAME_HEADER_SIZE) {
            return Optional.empty();
        }
        // skip magic
        buffer.readShort();
        short flags = buffer.readShort();
        boolean outOfOrderResponse = (flags & FLAG_SUPPORT_OUT_OF_ORDER_MASK) == 1;
        int headerSequenceId = buffer.readInt();
        int headerSize = buffer.readShort() << 2;

        if (buffer.readableBytes() < headerSize) {
            return Optional.empty();
        }

        byte protocolId = buffer.getByte(buffer.readerIndex());
        Protocol protocol = Protocol.getProtocolByHeaderTransportId(protocolId);

        buffer.skipBytes(headerSize);
        SimpleFrameInfoDecoder simpleFrameInfoDecoder = new SimpleFrameInfoDecoder(HEADER, protocol,
                outOfOrderResponse);
        Optional<FrameInfo> frameInfo = simpleFrameInfoDecoder.tryDecodeFrameInfo(buffer);
        if (frameInfo.isPresent()) {
            int messageSequenceId = frameInfo.get().getSequenceId();
            checkArgument(headerSequenceId == messageSequenceId,
                    "Sequence ids don't match. headerSequenceId: %s. messageSequenceId: %s", headerSequenceId,
                    messageSequenceId);
        }
        return frameInfo;
    } finally {
        buffer.release();
    }
}

From source file:io.airlift.drift.transport.netty.codec.TestThriftFramedDecoder.java

License:Apache License

@Test
public void testChunked() {
    byte[] first = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    byte[] second = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    byte[] third = new byte[] { 5, 4, 3 };

    try (TestingPooledByteBufAllocator allocator = new TestingPooledByteBufAllocator()) {
        ByteBuf buffer = allocator.buffer(1024);

        ThriftFramedDecoder decoder = createDecoder(second.length);
        ByteBuf decoded = decode(decoder, buffer);
        assertNull(decoded);//  w w w .ja v  a 2  s .  c om

        // write a partial frame length
        buffer.writeByte(0xAB);
        decoded = decode(decoder, buffer);
        assertNull(decoded);
        assertEquals(buffer.readerIndex(), 0);
        assertEquals(buffer.writerIndex(), 1);

        // write only a frame length
        buffer.writerIndex(0);
        buffer.writeInt(first.length);
        decoded = decode(decoder, buffer);
        assertNull(decoded);
        assertEquals(buffer.readerIndex(), 0);
        assertEquals(buffer.writerIndex(), Integer.BYTES);

        // start writing a frame
        buffer.writeBytes(first, 0, 5);
        decoded = decode(decoder, buffer);
        assertNull(decoded);
        assertEquals(buffer.readerIndex(), 0);
        assertEquals(buffer.writerIndex(), Integer.BYTES + 5);

        // finish writing a frame
        buffer.writeBytes(first, 5, first.length - 5);
        decoded = decode(decoder, buffer);
        assertNotNull(decoded);
        assertContentEquals(decoded, first);
        decoded.release();

        // write the first frame
        writeLengthPrefixedFrame(buffer, second);
        // start writing the second frame
        buffer.writeInt(third.length);
        buffer.writeBytes(third, 0, 1);
        // decode the first frame
        decoded = decode(decoder, buffer);
        assertNotNull(decoded);
        assertContentEquals(decoded, second);
        decoded.release();

        // try decode the second frame
        decoded = decode(decoder, buffer);
        assertNull(decoded);

        // finish writing the second frame
        buffer.writeBytes(third, 1, third.length - 1);
        decoded = decode(decoder, buffer);
        assertNotNull(decoded);
        assertContentEquals(decoded, third);
        decoded.release();

        assertEquals(buffer.readerIndex(), buffer.writerIndex());

        buffer.release();
    }
}

From source file:io.airlift.drift.transport.netty.codec.TestThriftFramedDecoder.java

License:Apache License

private static void assertContentEquals(ByteBuf buffer, byte[] expectedContent) {
    assertEquals(buffer.readableBytes(), expectedContent.length);
    byte[] actual = new byte[buffer.readableBytes()];
    buffer.getBytes(buffer.readerIndex(), actual);
    assertEquals(actual, expectedContent);
}

From source file:io.airlift.drift.transport.netty.codec.ThriftFramedDecoder.java

License:Apache License

private Optional<ByteBuf> decode(ByteBuf buffer) {
    if (bytesToDiscard > 0) {
        discardTooLongFrame(buffer);// w  w  w .j  a va 2 s. c  o m
        return Optional.empty();
    }

    int initialReaderIndex = buffer.readerIndex();

    if (buffer.readableBytes() < Integer.BYTES) {
        return Optional.empty();
    }
    long frameSizeInBytes = buffer.readUnsignedInt();

    if (frameSizeInBytes > maxFrameSizeInBytes) {
        // this invocation doesn't move the readerIndex
        Optional<FrameInfo> frameInfo = frameInfoDecoder.tryDecodeFrameInfo(buffer);
        if (frameInfo.isPresent()) {
            tooLongFrameInfo = frameInfo;
            tooLongFrameSizeInBytes = frameSizeInBytes;
            bytesToDiscard = frameSizeInBytes;
            discardTooLongFrame(buffer);
            return Optional.empty();
        }
        // Basic frame info cannot be decoded and the max frame size is already exceeded.
        // Instead of waiting forever, fail without providing the sequence ID.
        if (buffer.readableBytes() >= maxFrameSizeInBytes) {
            tooLongFrameInfo = Optional.empty();
            tooLongFrameSizeInBytes = frameSizeInBytes;
            bytesToDiscard = frameSizeInBytes;
            discardTooLongFrame(buffer);
            return Optional.empty();
        }
        buffer.readerIndex(initialReaderIndex);
        return Optional.empty();
    }

    if (buffer.readableBytes() >= frameSizeInBytes) {
        // toIntExact must be safe, as frameSizeInBytes <= maxFrameSize
        ByteBuf frame = buffer.retainedSlice(buffer.readerIndex(), toIntExact(frameSizeInBytes));
        buffer.readerIndex(buffer.readerIndex() + toIntExact(frameSizeInBytes));
        return Optional.of(frame);
    }

    buffer.readerIndex(initialReaderIndex);
    return Optional.empty();
}

From source file:io.airlift.drift.transport.netty.codec.ThriftUnframedDecoder.java

License:Apache License

@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
    int frameOffset = buffer.readerIndex();
    TChannelBufferInputTransport transport = new TChannelBufferInputTransport(buffer.retain());
    try {/* w w w . j  a va  2 s.  co  m*/
        TProtocolReader protocolReader = protocol.createProtocol(transport);

        TMessage message = protocolReader.readMessageBegin();
        TProtocolUtil.skip(protocolReader, TType.STRUCT);
        protocolReader.readMessageEnd();

        int frameLength = buffer.readerIndex() - frameOffset;
        if (frameLength > maxFrameSize) {
            FrameInfo frameInfo = new FrameInfo(message.getName(), message.getType(), message.getSequenceId(),
                    UNFRAMED, protocol, assumeClientsSupportOutOfOrderResponses);
            ctx.fireExceptionCaught(
                    new FrameTooLargeException(Optional.of(frameInfo), frameLength, maxFrameSize));
        }

        out.add(buffer.slice(frameOffset, frameLength).retain());
    } catch (Throwable th) {
        buffer.readerIndex(frameOffset);
    } finally {
        transport.release();
    }
}

From source file:io.airlift.drift.transport.netty.HeaderMessageEncoding.java

License:Apache License

@Override
public OptionalInt extractResponseSequenceId(ByteBuf buffer) {
    if (buffer.readableBytes() < HEADER_SEQUENCE_ID_OFFSET + Integer.BYTES) {
        return OptionalInt.empty();
    }/*from w ww  .ja  v a  2  s  .  c om*/
    return OptionalInt.of(buffer.getInt(buffer.readerIndex() + HEADER_SEQUENCE_ID_OFFSET));
}

From source file:io.airlift.drift.transport.netty.server.OptionalSslHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) {
    // minimum bytes required to detect ssl
    if (in.readableBytes() < SSL_RECORD_HEADER_LENGTH) {
        return;//from   www  .  ja  v  a 2s .  c  om
    }

    ChannelPipeline pipeline = context.pipeline();
    if (isTls(in, in.readerIndex())) {
        pipeline.replace(this, "ssl", sslContext.newHandler(context.alloc()));
    } else {
        pipeline.remove(this);
    }
}

From source file:io.airlift.drift.transport.netty.server.ThriftProtocolDetection.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) {
    // minimum bytes required to detect framing
    if (in.readableBytes() < 4) {
        return;/*  w  w w . j a  v  a  2  s.co m*/
    }

    int magic = in.getInt(in.readerIndex());

    // HTTP not supported
    if (magic == HTTP_POST_MAGIC) {
        in.clear();
        context.close();
        return;
    }

    // Unframed transport magic starts with the high byte set, whereas framed and header
    // both start with the frame size which must be a positive int
    if ((magic & UNFRAMED_MESSAGE_MASK) == UNFRAMED_MESSAGE_FLAG) {
        Optional<Protocol> protocol = detectProtocol(magic);
        if (!protocol.isPresent()) {
            in.clear();
            context.close();
            return;
        }

        switchToTransport(context, UNFRAMED, protocol);
        return;
    }

    // The second int is used to determine if the transport is framed or header
    if (in.readableBytes() < 8) {
        return;
    }

    int magic2 = in.getInt(in.readerIndex() + 4);
    if ((magic2 & HEADER_MAGIC_MASK) == HEADER_MAGIC) {
        switchToTransport(context, HEADER, Optional.empty());
        return;
    }

    Optional<Protocol> protocol = detectProtocol(magic2);
    if (!protocol.isPresent()) {
        in.clear();
        context.close();
        return;
    }

    switchToTransport(context, FRAMED, protocol);
}