Example usage for io.netty.buffer ByteBuf skipBytes

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

Introduction

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

Prototype

public abstract ByteBuf skipBytes(int length);

Source Link

Document

Increases the current readerIndex by the specified length in this buffer.

Usage

From source file:io.moquette.parser.netty.TestUtils.java

License:Open Source License

/**
 * Verify the presence of the given string starting from the current position
 * inside the buffer./* www.j  a  v  a  2 s .  c om*/
 */
static void verifyString(String str, ByteBuf buff) throws UnsupportedEncodingException {
    ByteBuf tmpBuff = Unpooled.buffer(2);
    byte[] raw = str.getBytes("UTF-8");
    tmpBuff.writeShort(raw.length);
    tmpBuff.writeBytes(raw);
    int buffLen = raw.length + 2;
    verifyByteBuf(tmpBuff, buff.slice(buff.readerIndex(), buffLen));
    buff.skipBytes(buffLen);
}

From source file:io.moquette.Utils.java

License:Open Source License

static boolean checkHeaderAvailability(ByteBuf in) {
    if (in.readableBytes() < 1) {
        return false;
    }/*from   w w  w  . j  a  v  a 2  s  . c  om*/
    // byte h1 = in.get();
    // byte messageType = (byte) ((h1 & 0x00F0) >> 4);
    in.skipBytes(1); // skip the messageType byte

    int remainingLength = Utils.decodeRemainingLenght(in);
    if (remainingLength == -1) {
        return false;
    }

    // check remaining length
    if (in.readableBytes() < remainingLength) {
        return false;
    }

    // return messageType == type ? MessageDecoderResult.OK : MessageDecoderResult.NOT_OK;
    return true;
}

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  a2  s.  com*/
 * 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.reactiverse.pgclient.impl.RowResultDecoder.java

License:Apache License

@Override
public void decodeRow(int len, ByteBuf in) {
    if (container == null) {
        container = collector.supplier().get();
    }//from  ww  w  .  j av  a2s  . co m
    if (singleton) {
        if (row == null) {
            row = new RowImpl(desc);
        } else {
            row.clear();
        }
    } else {
        row = new RowImpl(desc);
    }
    Row row = new RowImpl(desc);
    for (int c = 0; c < len; ++c) {
        int length = in.readInt();
        Object decoded = null;
        if (length != -1) {
            ColumnDesc columnDesc = desc.columns()[c];
            if (columnDesc.getDataFormat() == DataFormat.BINARY) {
                decoded = DataTypeCodec.decodeBinary(columnDesc.getDataType(), in.readerIndex(), length, in);
            } else {
                decoded = DataTypeCodec.decodeText(columnDesc.getDataType(), in.readerIndex(), length, in);
            }
            in.skipBytes(length);
        }
        row.addValue(decoded);
    }
    accumulator.accept(container, row);
    size++;
}

From source file:io.servicecomb.foundation.vertx.server.TcpParser.java

License:Apache License

protected void onParse(Buffer buffer) {
    switch (status) {
    case TCP_HEADER:
        ByteBuf buf = buffer.getByteBuf();
        if (!firstNEqual(TCP_MAGIC, buf.array(), TCP_MAGIC.length)) {
            reset();/*from  ww  w.  j a  v a2 s.com*/
            return;
        }

        buf.skipBytes(TCP_MAGIC.length);
        msgId = buf.readLong();
        totalLen = buf.readInt();
        headerLen = buf.readInt();

        if (totalLen == 0) {
            onReadOnePackage(null, null);
            return;
        }

        parser.fixedSizeMode(totalLen);
        status = ParseStatus.TCP_PAYLOAD;
        break;

    case TCP_PAYLOAD:
        Buffer headerBuffer = buffer.slice(0, headerLen);
        Buffer bodyBuffer = buffer.slice(headerLen, buffer.length());
        onReadOnePackage(headerBuffer, bodyBuffer);
        break;

    default:
        break;
    }
}

From source file:io.vertx.core.dns.impl.decoder.RecordDecoder.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   ww  w.  j a v  a2 s  . co  m*/
 */
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.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache 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 in the byte buffer containing the DNS packet
 * @return the domain name for an entry/*  w  ww  .ja  v  a  2 s  .c o  m*/
 */
public static String decodeName(ByteBuf in) {
    int position = -1;
    int checked = 0;
    final int end = in.writerIndex();
    final int readable = in.readableBytes();

    // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems
    // some servers do not respect this for empty names. So just workaround this and return an empty name in this
    // case.
    //
    // See:
    // - https://github.com/netty/netty/issues/5014
    // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1
    if (readable == 0) {
        return ".";
    }

    final StringBuilder name = new StringBuilder(readable << 1);
    while (in.isReadable()) {
        final int len = in.readUnsignedByte();
        final boolean pointer = (len & 0xc0) == 0xc0;
        if (pointer) {
            if (position == -1) {
                position = in.readerIndex() + 1;
            }

            if (!in.isReadable()) {
                throw new CorruptedFrameException("truncated pointer in a name");
            }

            final int next = (len & 0x3f) << 8 | in.readUnsignedByte();
            if (next >= end) {
                throw new CorruptedFrameException("name has an out-of-range pointer");
            }
            in.readerIndex(next);

            // check for loops
            checked += 2;
            if (checked >= end) {
                throw new CorruptedFrameException("name contains a loop.");
            }
        } else if (len != 0) {
            if (!in.isReadable(len)) {
                throw new CorruptedFrameException("truncated label in a name");
            }
            name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
            in.skipBytes(len);
        } else { // len == 0
            break;
        }
    }

    if (position != -1) {
        in.readerIndex(position);
    }

    if (name.length() == 0) {
        return ".";
    }

    if (name.charAt(name.length() - 1) != '.') {
        name.append('.');
    }

    return name.toString();
}

From source file:jazmin.server.msg.codec.json.JSONDecoder.java

License:Open Source License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   buffer          the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created.//  w  w  w  .  java2s  . c  o  m
 */
protected ByteBuf decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eol = findEndOfLine(buffer);
    if (!discarding) {
        if (eol >= 0) {
            final ByteBuf frame;
            final int length = eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;

            if (length > maxLength) {
                buffer.readerIndex(eol + delimLength);
                fail(ctx, length);
                return null;
            }

            if (stripDelimiter) {
                frame = buffer.readBytes(length);
                buffer.skipBytes(delimLength);
            } else {
                frame = buffer.readBytes(length + delimLength);
            }

            return frame;
        } else {
            final int length = buffer.readableBytes();
            if (length > maxLength) {
                discardedBytes = length;
                buffer.readerIndex(buffer.writerIndex());
                discarding = true;
                if (failFast) {
                    fail(ctx, "over " + discardedBytes);
                }
            }
            return null;
        }
    } else {
        if (eol >= 0) {
            final int length = discardedBytes + eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
            buffer.readerIndex(eol + delimLength);
            discardedBytes = 0;
            discarding = false;
            if (!failFast) {
                fail(ctx, length);
            }
        } else {
            discardedBytes = buffer.readableBytes();
            buffer.readerIndex(buffer.writerIndex());
        }
        return null;
    }
}

From source file:log.server.handler.EightLengthFieldDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   in              the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created./* w ww.jav a 2 s  .  co  m*/
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;

        failIfNecessary(false);
    }
    int m = in.readableBytes(), i = 0;
    while (i < m) {
        short digit = in.getUnsignedByte(i);
        if (digit == ' ')
            break;
        i++;
    }

    if (i == m) {
        byte[] tests = new byte[in.readableBytes()];
        in.readBytes(tests);
        String log = new String(tests);
        logger.info("readablebytes======konggechangdu==" + log);
        return null;
    }
    lengthFieldLength = i;

    if (in.readableBytes() < lengthFieldLength) {
        logger.info("readablebytes<<<<<lengthFieldLength");
        return null;
    }
    initialBytesToStrip = i + lengthAdjustment;
    lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength;
    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        byte[] tests = new byte[in.readableBytes()];
        in.readBytes(tests);
        String log = new String(tests);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength + "log" + log);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        long discard = frameLength - in.readableBytes();
        tooLongFrameLength = frameLength;

        if (discard < 0) {
            // buffer contains more bytes then the frameLength so we can discard all now
            in.skipBytes((int) frameLength);
        } else {
            // Enter the discard mode and discard everything received so far.
            discardingTooLongFrame = true;
            bytesToDiscard = discard;
            in.skipBytes(in.readableBytes());
        }
        failIfNecessary(true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    in.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:me.ferrybig.javacoding.webmapper.netty.WebServerHandler.java

public Optional<Object> decodeRequest(Optional<String> contentTypeHeader, ByteBuf post) {
    try {/*from w w w .j  a va  2 s . c o m*/
        if (!contentTypeHeader.isPresent()) {

            return Optional.empty();
        }
        int responseSize = post.readableBytes();
        if (responseSize > 1 * 1024 * 1024) {
            return Optional.empty();
        }
        String[] header = contentTypeHeader.get().split(";");
        String type = header[0].trim();
        String charset = "UFT-8";
        for (int i = 1; i < header.length; i++) {
            String[] split = header[i].split("=");
            if (split.length != 2) {
                continue;
            }
            split[0] = split[0].trim();
            split[1] = split[1].trim();
            if (split[0].equals("charset")) {
                charset = split[1];
            }
        }
        charset = charset.toUpperCase();
        Charset set = null;
        for (Map.Entry<String, Charset> key : Charset.availableCharsets().entrySet()) {
            if (charset.equals(key.getKey().toUpperCase())) {
                set = key.getValue();
                break;
            }
        }
        if (set == null) {
            return Optional.empty();
        }
        switch (type.toLowerCase()) {
        case "application/json": {
            String input = post.toString(set);
            try {
                return Optional.of(new JSONObject(input));
            } catch (JSONException ex) {
                return Optional.empty();
            }
        }
        case "application/x-www-form-urlencoded": {
            String input = post.toString(set);
            return Optional.of(new QueryStringDecoder(input));
        }
        default:
            return Optional.empty();
        }
    } finally {
        // Consume bytes remaining...
        post.skipBytes(post.readableBytes());
    }
}