Example usage for io.netty.buffer ByteBuf getUnsignedByte

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

Introduction

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

Prototype

public abstract short getUnsignedByte(int index);

Source Link

Document

Gets an unsigned byte at the specified absolute index in this buffer.

Usage

From source file:com.cc.nettytest.proxy.decoder.CCLengthFieldBasedFrameDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf inBuffer) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, inBuffer.readableBytes());
        inBuffer.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;
        failIfNecessary(ctx, false);//www. j  a v  a2s .com
        return null;
    }

    if (inBuffer.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = inBuffer.readerIndex() + lengthFieldOffset;
    long frameLength;
    switch (lengthFieldLength) {
    case 1:
        frameLength = inBuffer.getUnsignedByte(actualLengthFieldOffset);
        break;
    case 2:
        frameLength = inBuffer.getUnsignedShort(actualLengthFieldOffset);
        break;
    case 3:
        frameLength = inBuffer.getUnsignedMedium(actualLengthFieldOffset);
        break;
    case 4:
        frameLength = ByteBufUtil.swapInt((int) inBuffer.getUnsignedInt(actualLengthFieldOffset)); //SWAP FOR UIMANAGER
        break;
    case 8:
        frameLength = inBuffer.getLong(actualLengthFieldOffset);
        break;
    default:
        throw new Error("should not reach here");
    }

    if (frameLength < 0) {
        inBuffer.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

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

    if (frameLength > maxFrameLength) {
        // Enter the discard mode and discard everything received so far.
        discardingTooLongFrame = true;
        tooLongFrameLength = frameLength;
        bytesToDiscard = frameLength - inBuffer.readableBytes();
        inBuffer.skipBytes(inBuffer.readableBytes());
        failIfNecessary(ctx, true);
        return null;
    }

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

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

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

From source file:com.chat.common.netty.handler.decode.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
 * capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
 * decode the length field encoded differently.  Note that this method must not modify the state of the specified
 * buffer (e.g. {@code readerIndex}, {@code writerIndex}, and the content of the buffer.)
 *
 * @throws DecoderException if failed to decode the specified region
 *///www.  ja va 2 s .  c  o  m
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
    buf = buf.order(order);
    long frameLength;
    switch (length) {
    case 1:
        frameLength = buf.getUnsignedByte(offset);
        break;
    case 2:
        frameLength = buf.getUnsignedShort(offset);
        break;
    case 3:
        frameLength = buf.getUnsignedMedium(offset);
        break;
    case 4:
        frameLength = buf.getUnsignedInt(offset);
        break;
    case 8:
        frameLength = buf.getLong(offset);
        break;
    default:
        throw new DecoderException(
                "unsupported lengthFieldLength: " + lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
    }
    return frameLength;
}

From source file:com.chiorichan.http.ssl.SniNegotiator.java

License:Mozilla Public License

private String sniHostNameFromHandshakeInfo(ByteBuf in) {
    int readerIndex = in.readerIndex();
    try {/* w  ww . j a  v  a2s .co  m*/
        int command = in.getUnsignedByte(readerIndex);

        // tls, but not handshake command
        switch (command) {
        case SslConstants.SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC:
        case SslConstants.SSL_CONTENT_TYPE_ALERT:
        case SslConstants.SSL_CONTENT_TYPE_APPLICATION_DATA:
            return null;
        case SslConstants.SSL_CONTENT_TYPE_HANDSHAKE:
            break;
        default:
            //not tls or sslv3, do not try sni
            handshaken = true;
            return null;
        }

        int majorVersion = in.getUnsignedByte(readerIndex + 1);

        // SSLv3 or TLS
        if (majorVersion == 3) {
            int packetLength = in.getUnsignedShort(readerIndex + 3) + 5;

            if (in.readableBytes() >= packetLength) {
                // decode the ssl client hello packet
                // we have to skip some var-length fields
                int offset = readerIndex + 43;

                int sessionIdLength = in.getUnsignedByte(offset);
                offset += sessionIdLength + 1;

                int cipherSuitesLength = in.getUnsignedShort(offset);
                offset += cipherSuitesLength + 2;

                int compressionMethodLength = in.getUnsignedByte(offset);
                offset += compressionMethodLength + 1;

                int extensionsLength = in.getUnsignedShort(offset);
                offset += 2;
                int extensionsLimit = offset + extensionsLength;

                while (offset < extensionsLimit) {
                    int extensionType = in.getUnsignedShort(offset);
                    offset += 2;

                    int extensionLength = in.getUnsignedShort(offset);
                    offset += 2;

                    // SNI
                    if (extensionType == 0) {
                        handshaken = true;
                        int serverNameType = in.getUnsignedByte(offset + 2);
                        if (serverNameType == 0) {
                            int serverNameLength = in.getUnsignedShort(offset + 3);
                            return in.toString(offset + 5, serverNameLength, CharsetUtil.UTF_8);
                        } else
                            // invalid enum value
                            return null;
                    }

                    offset += extensionLength;
                }

                handshaken = true;
                return null;
            } else
                // client hello incomplete
                return null;
        } else {
            handshaken = true;
            return null;
        }
    } catch (Throwable e) {
        // unexpected encoding, ignore sni and use default
        if (logger.isDebugEnabled())
            logger.debug("Unexpected client hello packet: " + ByteBufUtil.hexDump(in), e);
        handshaken = true;
        return null;
    }
}

From source file:com.chiorichan.util.ObjectUtil.java

License:Mozilla Public License

public static String hexDump(ByteBuf buf, int highlightIndex) {
    if (buf == null)
        return "Buffer: null!";

    if (buf.capacity() < 1) {
        return "Buffer: 0B!";
    }//w ww.j  av  a  2  s.  c  om

    StringBuilder dump = new StringBuilder();

    final int startIndex = 0;
    final int endIndex = buf.capacity();
    final int length = endIndex - startIndex;
    final int fullRows = length >>> 4;
    final int remainder = length & 0xF;

    int highlightRow = -1;

    dump.append(NEWLINE + "         +-------------------------------------------------+" + NEWLINE
            + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" + NEWLINE
            + "+--------+-------------------------------------------------+----------------+");

    if (highlightIndex > 0) {
        highlightRow = highlightIndex >>> 4;
        highlightIndex = highlightIndex - (16 * highlightRow) - 1;

        dump.append(NEWLINE + "|        |" + Strings.repeat("   ", highlightIndex) + " $$"
                + Strings.repeat("   ", 15 - highlightIndex));
        dump.append(" |" + Strings.repeat(" ", highlightIndex) + "$" + Strings.repeat(" ", 15 - highlightIndex)
                + "|");
    }

    // Dump the rows which have 16 bytes.
    for (int row = 0; row < fullRows; row++) {
        int rowStartIndex = row << 4;

        // Per-row prefix.
        appendHexDumpRowPrefix(dump, row, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + 16;
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        }
        dump.append(" |");

        // ASCII dump
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        }
        dump.append('|');

        if (highlightIndex > 0 && highlightRow == row + 1)
            dump.append(" <--");
    }

    // Dump the last row which has less than 16 bytes.
    if (remainder != 0) {
        int rowStartIndex = fullRows << 4;
        appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + remainder;
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        }
        dump.append(HEXPADDING[remainder]);
        dump.append(" |");

        // Ascii dump
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        }
        dump.append(BYTEPADDING[remainder]);
        dump.append('|');

        if (highlightIndex > 0 && highlightRow > fullRows + 1)
            dump.append(" <--");
    }

    dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+");

    return dump.toString();
}

From source file:com.chiorichan.util.ServerFunc.java

License:Mozilla Public License

public static String hexDump(ByteBuf buf, int highlightIndex) {
    if (buf == null)
        return "Buffer: null!";

    if (buf.capacity() < 1)
        return "Buffer: 0B!";

    StringBuilder dump = new StringBuilder();

    final int startIndex = 0;
    final int endIndex = buf.capacity();
    final int length = endIndex - startIndex;
    final int fullRows = length >>> 4;
    final int remainder = length & 0xF;

    int highlightRow = -1;

    dump.append(NEWLINE + "         +-------------------------------------------------+" + NEWLINE
            + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" + NEWLINE
            + "+--------+-------------------------------------------------+----------------+");

    if (highlightIndex > 0) {
        highlightRow = highlightIndex >>> 4;
        highlightIndex = highlightIndex - 16 * highlightRow - 1;

        dump.append(NEWLINE + "|        |" + Strings.repeat("   ", highlightIndex) + " $$"
                + Strings.repeat("   ", 15 - highlightIndex));
        dump.append(" |" + Strings.repeat(" ", highlightIndex) + "$" + Strings.repeat(" ", 15 - highlightIndex)
                + "|");
    }/*from  ww w  .  j  av a2 s . c  o m*/

    // Dump the rows which have 16 bytes.
    for (int row = 0; row < fullRows; row++) {
        int rowStartIndex = row << 4;

        // Per-row prefix.
        appendHexDumpRowPrefix(dump, row, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + 16;
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        dump.append(" |");

        // ASCII dump
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        dump.append('|');

        if (highlightIndex > 0 && highlightRow == row + 1)
            dump.append(" <--");
    }

    // Dump the last row which has less than 16 bytes.
    if (remainder != 0) {
        int rowStartIndex = fullRows << 4;
        appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + remainder;
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        dump.append(HEXPADDING[remainder]);
        dump.append(" |");

        // Ascii dump
        for (int j = rowStartIndex; j < rowEndIndex; j++)
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        dump.append(BYTEPADDING[remainder]);
        dump.append('|');

        if (highlightIndex > 0 && highlightRow > fullRows + 1)
            dump.append(" <--");
    }

    dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+");

    return dump.toString();
}

From source file:com.digitalpetri.opcua.stack.core.channel.ChunkDecoder.java

License:Apache License

private int getPaddingSize(int cipherTextBlockSize, int signatureSize, ByteBuf buffer) {
    int lastPaddingByteOffset = buffer.readableBytes() - signatureSize - 1;

    return cipherTextBlockSize <= 256 ? buffer.getUnsignedByte(lastPaddingByteOffset) + 1
            : buffer.getUnsignedShort(lastPaddingByteOffset - 1) + 2;
}

From source file:com.facebook.nifty.core.NettyThriftDecoder.java

License:Apache License

protected TTransport getTransport(Channel channel, ByteBuf cb) {
    ThriftTransportType type = (cb.getUnsignedByte(0) < 0x80) ? ThriftTransportType.FRAMED
            : ThriftTransportType.UNFRAMED;
    if (type == ThriftTransportType.FRAMED) {
        cb.skipBytes(4);/* ww  w. jav a2 s  .co m*/
    }
    return new TNiftyTransport(channel, new ThriftMessage(cb, type));
}

From source file:com.facebook.nifty.core.ThriftFrameDecoder.java

License:Apache License

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

    if (!buffer.isReadable()) {
        return;/*from  w w  w . j av  a2  s .  c  om*/
    }
    TTransport ttransport = null;
    short firstByte = buffer.getUnsignedByte(0);
    if (firstByte >= 0x80) {
        // A non-zero MSB for the first byte of the message implies the message starts with a
        // protocol id (and thus it is unframed).
        ttransport = tryDecodeUnframedMessage(ctx, buffer);
    } else if (buffer.readableBytes() < MESSAGE_FRAME_SIZE) {
        // Expecting a framed message, but not enough bytes available to read the frame size
        ttransport = null;
        log.error("Expecting a framed message, but not enough bytes available to read the frame size {}",
                MESSAGE_FRAME_SIZE);
    } else {
        // Messages with a zero MSB in the first byte are framed messages
        ttransport = tryDecodeFramedMessage(ctx, buffer);
    }
    if (ttransport != null) {
        out.add(ttransport);
    } else {
        log.error("ttransport is null , firstByte is {}", firstByte);
    }
}

From source file:com.flysoloing.learning.network.netty.portunification.PortUnificationServerHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Will use the first five bytes to detect a protocol.
    if (in.readableBytes() < 5) {
        return;/* w w  w.  ja  v  a2s  . c o m*/
    }

    if (isSsl(in)) {
        enableSsl(ctx);
    } else {
        final int magic1 = in.getUnsignedByte(in.readerIndex());
        final int magic2 = in.getUnsignedByte(in.readerIndex() + 1);
        if (isGzip(magic1, magic2)) {
            enableGzip(ctx);
        } else if (isHttp(magic1, magic2)) {
            switchToHttp(ctx);
        } else if (isFactorial(magic1)) {
            switchToFactorial(ctx);
        } else {
            // Unknown protocol; discard everything and close the connection.
            in.clear();
            ctx.close();
        }
    }
}

From source file:com.github.nettybook.ch0.LoggingHandler.java

License:Apache License

/**
 * Appends the prettifies multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified
 * {@link StringBuilder}.//ww  w. j a  va  2 s.  c  om
 */
protected static void appendHexDump(StringBuilder dump, ByteBuf buf) {
    dump.append(NEWLINE + "         +-------------------------------------------------+" + NEWLINE
            + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" + NEWLINE
            + "+--------+-------------------------------------------------+----------------+");

    final int startIndex = buf.readerIndex();
    final int endIndex = buf.writerIndex();
    final int length = endIndex - startIndex;
    final int fullRows = length >>> 4;
    final int remainder = length & 0xF;

    // Dump the rows which have 16 bytes.
    for (int row = 0; row < fullRows; row++) {
        int rowStartIndex = row << 4;

        // Per-row prefix.
        appendHexDumpRowPrefix(dump, row, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + 16;
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        }
        dump.append(" |");

        // ASCII dump
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        }
        dump.append('|');
    }

    // Dump the last row which has less than 16 bytes.
    if (remainder != 0) {
        int rowStartIndex = fullRows << 4;
        appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

        // Hex dump
        int rowEndIndex = rowStartIndex + remainder;
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2HEX[buf.getUnsignedByte(j)]);
        }
        dump.append(HEXPADDING[remainder]);
        dump.append(" |");

        // Ascii dump
        for (int j = rowStartIndex; j < rowEndIndex; j++) {
            dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]);
        }
        dump.append(BYTEPADDING[remainder]);
        dump.append('|');
    }

    dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+");
}