Example usage for io.netty.buffer ByteBuf readBytes

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

Introduction

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

Prototype

public abstract ByteBuf readBytes(ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the current readerIndex until the destination's position reaches its limit, and increases the readerIndex by the number of the transferred bytes.

Usage

From source file:com.twitter.http2.HttpFrameDecoder.java

License:Apache License

/**
 * Decode the byte buffer./*from w  w  w  . ja  v a2  s .  c  o  m*/
 */
public void decode(ByteBuf buffer) {
    boolean endStream;
    boolean endSegment;
    int minLength;
    int dependency;
    int weight;
    boolean exclusive;
    int errorCode;

    while (true) {
        switch (state) {
        case READ_CONNECTION_HEADER:
            while (buffer.isReadable()) {
                byte b = buffer.readByte();
                if (b != CLIENT_CONNECTION_PREFACE[length++]) {
                    state = State.FRAME_ERROR;
                    delegate.readFrameError("Invalid Connection Header");
                    return;
                }

                if (length == CLIENT_CONNECTION_PREFACE.length) {
                    state = State.READ_FRAME_HEADER;
                    break;
                }
            }
            if (buffer.isReadable()) {
                break;
            } else {
                return;
            }

        case READ_FRAME_HEADER:
            // Wait until entire header is readable
            if (buffer.readableBytes() < HTTP_FRAME_HEADER_SIZE) {
                return;
            }

            // Read frame header fields
            readFrameHeader(buffer);

            // TODO(jpinner) Sec 4.2 FRAME_SIZE_ERROR

            if (!isValidFrameHeader(length, type, flags, streamId)) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Frame Header");
            } else if (frameHasPadding(type, flags)) {
                state = State.READ_PADDING_LENGTH;
            } else {
                paddingLength = 0;
                state = getNextState(length, type);
            }
            break;

        case READ_PADDING_LENGTH:
            if (buffer.readableBytes() < 1) {
                return;
            }

            paddingLength = buffer.readUnsignedByte();
            --length;

            if (!isValidPaddingLength(length, type, flags, paddingLength)) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Frame Padding Length");
            } else {
                state = getNextState(length, type);
            }
            break;

        case READ_DATA_FRAME:
            endStream = hasFlag(flags, HTTP_FLAG_END_STREAM);
            state = State.READ_DATA;
            if (hasFlag(flags, HTTP_FLAG_PADDED)) {
                delegate.readDataFramePadding(streamId, endStream, paddingLength + 1);
            }
            break;

        case READ_DATA:
            // Generate data frames that do not exceed maxChunkSize
            // maxChunkSize must be > 0 so we cannot infinitely loop
            int dataLength = Math.min(maxChunkSize, length - paddingLength);

            // Wait until entire frame is readable
            if (buffer.readableBytes() < dataLength) {
                return;
            }

            ByteBuf data = buffer.readBytes(dataLength);
            length -= dataLength;

            if (length == paddingLength) {
                if (paddingLength == 0) {
                    state = State.READ_FRAME_HEADER;
                } else {
                    state = State.SKIP_FRAME_PADDING;
                }
            }

            endStream = length == paddingLength && hasFlag(flags, HTTP_FLAG_END_STREAM);
            endSegment = length == paddingLength && hasFlag(flags, HTTP_FLAG_END_SEGMENT);

            delegate.readDataFrame(streamId, endStream, endSegment, data);
            break;

        case READ_HEADERS_FRAME:
            minLength = 0;
            if (hasFlag(flags, HTTP_FLAG_PRIORITY)) {
                minLength = 5;
            }
            if (buffer.readableBytes() < minLength) {
                return;
            }

            endStream = hasFlag(flags, HTTP_FLAG_END_STREAM);
            endSegment = hasFlag(flags, HTTP_FLAG_END_SEGMENT);

            exclusive = false;
            dependency = 0;
            weight = 16;
            if (hasFlag(flags, HTTP_FLAG_PRIORITY)) {
                dependency = getSignedInt(buffer, buffer.readerIndex());
                buffer.skipBytes(4);
                weight = buffer.readUnsignedByte() + 1;
                if (dependency < 0) {
                    dependency = dependency & 0x7FFFFFFF;
                    exclusive = true;
                }
                length -= 5;
            }

            state = State.READ_HEADER_BLOCK;
            delegate.readHeadersFrame(streamId, endStream, endSegment, exclusive, dependency, weight);
            break;

        case READ_PRIORITY_FRAME:
            if (buffer.readableBytes() < length) {
                return;
            }

            exclusive = false;
            dependency = getSignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(4);
            weight = buffer.readUnsignedByte() + 1;
            if (dependency < 0) {
                dependency = dependency & 0x7FFFFFFF;
                exclusive = true;
            }

            state = State.READ_FRAME_HEADER;
            delegate.readPriorityFrame(streamId, exclusive, dependency, weight);
            break;

        case READ_RST_STREAM_FRAME:
            if (buffer.readableBytes() < length) {
                return;
            }

            errorCode = getSignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(length);

            state = State.READ_FRAME_HEADER;
            delegate.readRstStreamFrame(streamId, errorCode);
            break;

        case READ_SETTINGS_FRAME:
            boolean ack = hasFlag(flags, HTTP_FLAG_ACK);

            state = State.READ_SETTING;
            delegate.readSettingsFrame(ack);
            break;

        case READ_SETTING:
            if (length == 0) {
                state = State.READ_FRAME_HEADER;
                delegate.readSettingsEnd();
                break;
            }

            if (buffer.readableBytes() < 6) {
                return;
            }

            int id = getUnsignedShort(buffer, buffer.readerIndex());
            int value = getSignedInt(buffer, buffer.readerIndex() + 2);
            buffer.skipBytes(6);
            length -= 6;

            delegate.readSetting(id, value);
            break;

        case READ_PUSH_PROMISE_FRAME:
            if (buffer.readableBytes() < 4) {
                return;
            }

            int promisedStreamId = getUnsignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(4);
            length -= 4;

            if (promisedStreamId == 0) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Promised-Stream-ID");
            } else {
                state = State.READ_HEADER_BLOCK;
                delegate.readPushPromiseFrame(streamId, promisedStreamId);
            }
            break;

        case READ_PING_FRAME:
            if (buffer.readableBytes() < length) {
                return;
            }

            long ping = getSignedLong(buffer, buffer.readerIndex());
            buffer.skipBytes(length);

            boolean pong = hasFlag(flags, HTTP_FLAG_ACK);

            state = State.READ_FRAME_HEADER;
            delegate.readPingFrame(ping, pong);
            break;

        case READ_GOAWAY_FRAME:
            if (buffer.readableBytes() < 8) {
                return;
            }

            int lastStreamId = getUnsignedInt(buffer, buffer.readerIndex());
            errorCode = getSignedInt(buffer, buffer.readerIndex() + 4);
            buffer.skipBytes(8);
            length -= 8;

            if (length == 0) {
                state = State.READ_FRAME_HEADER;
            } else {
                paddingLength = length;
                state = State.SKIP_FRAME_PADDING;
            }
            delegate.readGoAwayFrame(lastStreamId, errorCode);
            break;

        case READ_WINDOW_UPDATE_FRAME:
            // Wait until entire frame is readable
            if (buffer.readableBytes() < length) {
                return;
            }

            int windowSizeIncrement = getUnsignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(length);

            if (windowSizeIncrement == 0) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Window Size Increment");
            } else {
                state = State.READ_FRAME_HEADER;
                delegate.readWindowUpdateFrame(streamId, windowSizeIncrement);
            }
            break;

        case READ_CONTINUATION_FRAME_HEADER:
            // Wait until entire frame header is readable
            if (buffer.readableBytes() < HTTP_FRAME_HEADER_SIZE) {
                return;
            }

            // Read and validate continuation frame header fields
            int prevStreamId = streamId;
            readFrameHeader(buffer);

            // TODO(jpinner) Sec 4.2 FRAME_SIZE_ERROR
            // TODO(jpinner) invalid flags

            if (type != HTTP_CONTINUATION_FRAME || streamId != prevStreamId) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Continuation Frame");
            } else {
                paddingLength = 0;
                state = State.READ_HEADER_BLOCK;
            }
            break;

        case READ_HEADER_BLOCK:
            if (length == paddingLength) {
                boolean endHeaders = hasFlag(flags, HTTP_FLAG_END_HEADERS);
                if (endHeaders) {
                    state = State.SKIP_FRAME_PADDING;
                    delegate.readHeaderBlockEnd();
                } else {
                    state = State.SKIP_FRAME_PADDING_CONTINUATION;
                }
                break;
            }

            if (!buffer.isReadable()) {
                return;
            }

            int readableBytes = Math.min(buffer.readableBytes(), length - paddingLength);
            ByteBuf headerBlockFragment = buffer.readBytes(readableBytes);
            length -= readableBytes;

            delegate.readHeaderBlock(headerBlockFragment);
            break;

        case SKIP_FRAME_PADDING:
            int numBytes = Math.min(buffer.readableBytes(), length);
            buffer.skipBytes(numBytes);
            length -= numBytes;
            if (length == 0) {
                state = State.READ_FRAME_HEADER;
                break;
            }
            return;

        case SKIP_FRAME_PADDING_CONTINUATION:
            int numPaddingBytes = Math.min(buffer.readableBytes(), length);
            buffer.skipBytes(numPaddingBytes);
            length -= numPaddingBytes;
            if (length == 0) {
                state = State.READ_CONTINUATION_FRAME_HEADER;
                break;
            }
            return;

        case FRAME_ERROR:
            buffer.skipBytes(buffer.readableBytes());
            return;

        default:
            throw new Error("Shouldn't reach here.");
        }
    }
}

From source file:com.uber.tchannel.checksum.Checksums.java

License:Open Source License

public static long calculateChecksum(CallFrame msg, long digestSeed) {

    // TODO: this is bad
    ByteBuf payloadCopy = msg.getPayload().slice();
    byte[] payloadBytes = new byte[msg.getPayloadSize()];
    payloadCopy.readBytes(payloadBytes);

    switch (msg.getChecksumType()) {

    case Adler32:
        Adler32 f = new Adler32();
        f.update((int) digestSeed);
        f.update(payloadBytes);//from  w ww  . j av a2s. com
        return f.getValue();
    case FarmhashFingerPrint32:
    case NoChecksum:
    case CRC32C:
    default:
        return 0;
    }

}

From source file:com.uber.tchannel.codecs.CodecUtils.java

License:Open Source License

public static String decodeString(ByteBuf buffer) {
    int valueLength = buffer.readUnsignedShort();
    byte[] valueBytes = new byte[valueLength];
    buffer.readBytes(valueBytes);
    return new String(valueBytes);
}

From source file:com.uber.tchannel.codecs.CodecUtils.java

License:Open Source License

public static String decodeSmallString(ByteBuf buffer) {
    int valueLength = buffer.readUnsignedByte();
    byte[] valueBytes = new byte[valueLength];
    buffer.readBytes(valueBytes);
    return new String(valueBytes);
}

From source file:com.uber.tchannel.messages.ThriftSerializer.java

License:Open Source License

@Override
public <T> T decodeBody(ByteBuf arg3, Class<T> bodyType) {

    try {/* w w  w  .jav  a 2 s  . co  m*/
        // Create a new instance of type 'T'
        T base = bodyType.newInstance();

        // Get byte[] from ByteBuf
        byte[] payloadBytes = new byte[arg3.readableBytes()];
        arg3.readBytes(payloadBytes);

        // Actually deserialize the payload
        TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
        deserializer.deserialize((TBase) base, payloadBytes);

        return base;
    } catch (InstantiationException | IllegalAccessException | TException e) {
        e.printStackTrace();
    }

    return null;

}

From source file:com.vethrfolnir.game.network.mu.crypt.MuDecoder.java

License:Open Source License

private static int DecodeBlock(ByteBuf buff, ByteBuf outBuff, int offset, int size) {
    // decripted size
    int index = 0;

    if ((size % 11) != 0) {
        log.warn("Cannot decrypt packet, it's already decrypted!: Size " + size + " = " + ((size % 11)));
        log.warn(PrintData.printData(buff.nioBuffer()));
        return -1;
    }/*www.  j  a va 2s . c o m*/

    ByteBuf encrypted = alloc.heapBuffer(11, 11).order(ByteOrder.LITTLE_ENDIAN);
    short[] uByteArray = new short[encrypted.capacity()];

    ByteBuf decrypted = alloc.heapBuffer(8, 8).order(ByteOrder.LITTLE_ENDIAN);
    ByteBuf converter = alloc.heapBuffer(4).order(ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < size; i += 11) {
        buff.readBytes(encrypted);

        //System.out.println("ENC: "+PrintData.printData(encrypted.nioBuffer()));
        int Result = BlockDecode(decrypted, getAsUByteArray(encrypted, uByteArray), converter,
                MuKeyFactory.getClientToServerPacketDecKeys());
        if (Result != -1) {
            //Buffer.BlockCopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            outBuff.writerIndex((offset - 1) + index);
            outBuff.writeBytes(decrypted);

            //outBuff.writeBytes(decrypted);

            decrypted.clear();
            encrypted.clear();
            converter.clear();
            //System.arraycopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            index += Result;
        }
    }

    return index;
}

From source file:com.vethrfolnir.game.network.mu.crypt.MuEncoder.java

License:Open Source License

public static void main(String[] args) {
    Corax.Install(new CoraxBuilder() {

        @Override//from  w w w. j  a  va 2s.  c  om
        protected void build(Corax corax) {
            CorvusConfig.WorkingDirectory = new File("./dist/GameServer");
            Corax.config().loadDirectory("/config");
            bind(AssetManager.class).as(Scope.Singleton);
            ;
        }
    });

    MuKeyFactory.parse();
    System.out.println("");

    //byte[] data = PacketUtils.hex2Bytes("C3 44 F3 03 42 E6 33 00 00 00 00 00 00 00 FA 00 00 00 00 00 00 01 25 84 0A 00 2D 00 32 00 12 00 28 00 56 00 56 00 59 00 59 00 C8 00 C8 00 10 00 20 00 12 00 B0 B4 1D 00 03 00 00 00 04 00 00 00 00 00 04 00");
    byte[] data = PacketUtils.hex2Bytes(
            "C4 00 2D 01 F3 10 03 00 00 00 12 00 00 10 00 FF FF FF FF FF 0C 14 08 1E 00 00 D0 00 FF FF FF FF FF 0D 14 10 1E 00 00 D0 00 FF FF FF FF");
    ByteBuf buff = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN);
    buff.writeBytes(data);

    ByteBuf out = EncodePacket(buff, 0x02);

    byte[] arr = new byte[out.readableBytes()];
    out.readBytes(arr);

    //System.out.println(PrintData.printData(out.nioBuffer()));
    //System.out.println("C3-65-22-EF-31-62-4B-D5-32-2F-B1-AA-9F-45-1B-08-45-D2-96-92-B1-51-37-02-45-1B-1F-83-13-D1-F3-9C-E6-67-52-9C-F7-0F-7C-CD-9B-E1-EC-B4-E8-DD-3D-33-0D-44-C2-73-52-48-4E-CD-F8-98-77-44-8B-99-FA-64-71-A6-FD-C8-35-92-35-B9-95-3D-A2-3C-81-C5-F0-0F-4E-1D-F0-81-34-72-2B-E8-C9-FC-36-05-31-36-80-D0-80-BB-0C-C2-FC");
    System.out.println("C3-0D-FE-53-65-66-18-AB-51-01-C1-4D-77");
    System.out.println(PacketUtils.byteArrayToHex(arr).toUpperCase());
}

From source file:com.vethrfolnir.game.network.mu.MuCyperDecoder.java

License:Open Source License

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

    if (!in.isReadable()) {
        MuClient client = ctx.channel().attr(MuClient.ClientKey).get();
        _log.warn("Client[" + client + "] sent an empty packet!");

        return; //XXX: is it critical?
    }//from   w w  w  . j av  a  2s .  c  o  m

    if (in.readableBytes() < 3) {
        return; // come back later
    }

    in.markReaderIndex();

    int opcode = in.readUnsignedByte();

    int lengthAt = 0;
    switch (opcode) {
    case 0xc1:
    case 0xc3:
        lengthAt = 1;
        break;
    case 0xc2:
    case 0xc4:
        lengthAt = 2;
        break;
    }

    //in.markReaderIndex();
    int rez = lengthAt > 1 ? in.readShort() : in.readUnsignedByte();
    in.resetReaderIndex();

    //System.out.println("1 Size[point="+(lengthAt > 1 ? "Short" : "Unsigned byte")+"]: "+rez+" opcode "+Integer.toHexString(opcode & 0xFF));
    if (in.readableBytes() < rez) {
        in.resetReaderIndex();
        return;
    }

    int header = in.getUnsignedByte(0);
    if (header == 0xC1 || header == 0xC2) {
        ByteBuf buff = ctx.alloc().heapBuffer(rez);
        in.readBytes(buff);
        out.add(DecodeXor32(buff));
    } else {
        out.add(DecodePacket(in));
    }
}

From source file:com.vethrfolnir.game.network.mu.packets.MuReadPacket.java

License:Open Source License

protected String readS(ByteBuf buff, int max) {
    try {/*w  ww.java  2s.  c o  m*/
        ByteBuf copy = buff.readBytes(max);
        String str = new String(copy.array(), "ISO-8859-1");
        copy.release();
        return str.trim();
    } catch (UnsupportedEncodingException e) {
        log.warn("Failed reading string!", e);
    }

    return null;
}

From source file:com.vethrfolnir.network.ReadPacket.java

License:Open Source License

/**
 * Don't forget to release the buffer//  ww w.j  av  a2  s .com
 * @param buff
 * @return
 */
protected ByteBuf readArray(ByteBuf buff) {
    return buff.readBytes(buff.readableBytes());
}