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:divconq.pgp.EncryptedFileStream.java

License:Open Source License

public void writeData(byte[] bytes, int offset, int len) {
    // the first time this is called we need to write headers - those headers
    // call into this method so clear flag immediately
    if (!this.writeFirst) {
        this.writeFirst = true;
        this.writeFirstLiteral(len);
    }/*w  ww.j  a v  a 2 s  .  c  om*/

    int remaining = len;
    int avail = this.packetsize - this.packetpos;

    // packetbuf may have data that has not yet been processed, so if we are doing any writes
    // we need to write the packet buffer first
    ByteBuf pbb = this.packetbuf;

    if (pbb != null) {
        int bbremaining = pbb.readableBytes();

        // only write if there is space available in current packet or if we have a total
        // amount of data larger than max packet size
        while ((bbremaining > 0) && ((avail > 0) || (bbremaining + remaining) >= MAX_PACKET_SIZE)) {
            // out of current packet space? create more packets
            if (avail == 0) {
                this.packetsize = MAX_PACKET_SIZE;
                this.packetpos = 0;

                this.writeDataInternal((byte) MAX_PARTIAL_LEN); // partial packet length

                avail = this.packetsize;
            }

            // figure out how much we can write to the current packet, write it, update indexes
            int alen = Math.min(avail, bbremaining);

            this.writeDataInternal(pbb.array(), pbb.arrayOffset() + pbb.readerIndex(), alen);

            pbb.skipBytes(alen);
            bbremaining = pbb.readableBytes();
            this.packetpos += alen;
            avail = this.packetsize - this.packetpos;

            // our formula always assumes that packetbuf starts at zero offset, anytime
            // we write out part of the packetbuf we either need to write it all and clear it
            // or we need to start with a new buffer with data starting at offset 0
            if (bbremaining == 0) {
                pbb.clear();
            } else {
                ByteBuf npb = Hub.instance.getBufferAllocator().heapBuffer(MAX_PACKET_SIZE);
                npb.writeBytes(pbb, bbremaining);
                this.packetbuf = npb;

                pbb.release();
                pbb = npb;
            }
        }
    }

    // only write if there is space available in current packet or if we have a total
    // amount of data larger than max packet size
    while ((remaining > 0) && ((avail > 0) || (remaining >= MAX_PACKET_SIZE))) {
        // out of current packet space? create more packets
        if (avail == 0) {
            this.packetsize = MAX_PACKET_SIZE;
            this.packetpos = 0;

            this.writeDataInternal((byte) MAX_PARTIAL_LEN); // partial packet length

            avail = this.packetsize;
        }

        // figure out how much we can write to the current packet, write it, update indexes
        int alen = Math.min(avail, remaining);

        this.writeDataInternal(bytes, offset, alen);

        remaining -= alen;
        offset += alen;
        this.packetpos += alen;
        avail = this.packetsize - this.packetpos;
    }

    // buffer remaining to build larger packet later
    if (remaining > 0) {
        if (this.packetbuf == null)
            this.packetbuf = Hub.instance.getBufferAllocator().heapBuffer(MAX_PACKET_SIZE);

        // add to new buffer or add to existing buffer, either way it should be less than max here
        this.packetbuf.writeBytes(bytes, offset, remaining);
    }
}

From source file:divconq.pgp.EncryptedFileStream.java

License:Open Source License

public void writeData(ByteBuf buf) {
    this.writeData(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
}

From source file:dorkbox.network.connection.KryoExtra.java

License:Apache License

/**
 * This is NOT ENCRYPTED (and is only done on the loopback connection!)
 *//*from  w  w w  . j av a 2 s. co  m*/
public synchronized void writeCompressed(final Connection_ connection, final ByteBuf buffer,
        final Object message) throws IOException {
    // required by RMI and some serializers to determine which connection wrote (or has info about) this object
    this.rmiSupport = connection.rmiSupport();

    ByteBuf objectOutputBuffer = this.tempBuffer;
    objectOutputBuffer.clear(); // always have to reset everything

    // write the object to a TEMP buffer! this will be compressed
    writer.setBuffer(objectOutputBuffer);

    writeClassAndObject(writer, message);

    // save off how much data the object took + magic byte
    int length = objectOutputBuffer.writerIndex();

    // NOTE: compression and encryption MUST work with byte[] because they use JNI!
    // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use
    // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it...
    // see:   https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf

    byte[] inputArray;
    int inputOffset;

    // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because
    // the buffer might be a slice of other buffer or a pooled buffer:
    //noinspection Duplicates
    if (objectOutputBuffer.hasArray() && objectOutputBuffer.array()[0] == objectOutputBuffer.getByte(0)
            && objectOutputBuffer.array().length == objectOutputBuffer.capacity()) {

        // we can use it...
        inputArray = objectOutputBuffer.array();
        inputArrayLength = -1; // this is so we don't REUSE this array accidentally!
        inputOffset = objectOutputBuffer.arrayOffset();
    } else {
        // we can NOT use it.
        if (length > inputArrayLength) {
            inputArrayLength = length;
            inputArray = new byte[length];
            this.inputArray = inputArray;
        } else {
            inputArray = this.inputArray;
        }

        objectOutputBuffer.getBytes(objectOutputBuffer.readerIndex(), inputArray, 0, length);
        inputOffset = 0;
    }

    ////////// compressing data
    // we ALWAYS compress our data stream -- because of how AES-GCM pads data out, the small input (that would result in a larger
    // output), will be negated by the increase in size by the encryption

    byte[] compressOutput = this.compressOutput;

    int maxLengthLengthOffset = 4; // length is never negative, so 4 is OK (5 means it's negative)
    int maxCompressedLength = compressor.maxCompressedLength(length);

    // add 4 so there is room to write the compressed size to the buffer
    int maxCompressedLengthWithOffset = maxCompressedLength + maxLengthLengthOffset;

    // lazy initialize the compression output buffer
    if (maxCompressedLengthWithOffset > compressOutputLength) {
        compressOutputLength = maxCompressedLengthWithOffset;
        compressOutput = new byte[maxCompressedLengthWithOffset];
        this.compressOutput = compressOutput;
    }

    // LZ4 compress. output offset max 4 bytes to leave room for length of tempOutput data
    int compressedLength = compressor.compress(inputArray, inputOffset, length, compressOutput,
            maxLengthLengthOffset, maxCompressedLength);

    // bytes can now be written to, because our compressed data is stored in a temp array.

    final int lengthLength = OptimizeUtilsByteArray.intLength(length, true);

    // correct input.  compression output is now buffer input
    inputArray = compressOutput;
    inputOffset = maxLengthLengthOffset - lengthLength;

    // now write the ORIGINAL (uncompressed) length to the front of the byte array (this is NOT THE BUFFER!). This is so we can use the FAST decompress version
    OptimizeUtilsByteArray.writeInt(inputArray, length, true, inputOffset);

    // have to copy over the orig data, because we used the temp buffer. Also have to account for the length of the uncompressed size
    buffer.writeBytes(inputArray, inputOffset, compressedLength + lengthLength);
}

From source file:dorkbox.network.connection.KryoExtra.java

License:Apache License

/**
 * This is NOT ENCRYPTED (and is only done on the loopback connection!)
 *//*from  www  .  j  ava 2s  . c o m*/
public Object readCompressed(final Connection_ connection, final ByteBuf buffer, int length)
        throws IOException {
    // required by RMI and some serializers to determine which connection wrote (or has info about) this object
    this.rmiSupport = connection.rmiSupport();

    ////////////////
    // Note: we CANNOT write BACK to the buffer as "temp" storage, since there could be additional data on it!
    ////////////////

    ByteBuf inputBuf = buffer;

    // get the decompressed length (at the beginning of the array)
    final int uncompressedLength = OptimizeUtilsByteBuf.readInt(buffer, true);
    final int lengthLength = OptimizeUtilsByteArray.intLength(uncompressedLength, true); // because 1-5 bytes for the decompressed size

    // have to adjust for uncompressed length
    length = length - lengthLength;

    ///////// decompress data -- as it's ALWAYS compressed

    // NOTE: compression and encryption MUST work with byte[] because they use JNI!
    // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use
    // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it...
    // see:   https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf

    byte[] inputArray;
    int inputOffset;

    // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because
    // the buffer might be a slice of other buffer or a pooled buffer:
    //noinspection Duplicates
    if (inputBuf.hasArray() && inputBuf.array()[0] == inputBuf.getByte(0)
            && inputBuf.array().length == inputBuf.capacity()) {

        // we can use it...
        inputArray = inputBuf.array();
        inputArrayLength = -1; // this is so we don't REUSE this array accidentally!
        inputOffset = inputBuf.arrayOffset() + lengthLength;
    } else {
        // we can NOT use it.
        if (length > inputArrayLength) {
            inputArrayLength = length;
            inputArray = new byte[length];
            this.inputArray = inputArray;
        } else {
            inputArray = this.inputArray;
        }

        inputBuf.getBytes(inputBuf.readerIndex(), inputArray, 0, length);
        inputOffset = 0;
    }

    // have to make sure to set the position of the buffer, since our conversion to array DOES NOT set the new reader index.
    buffer.readerIndex(buffer.readerIndex() + length);

    ///////// decompress data -- as it's ALWAYS compressed

    byte[] decompressOutputArray = this.decompressOutput;
    if (uncompressedLength > decompressOutputLength) {
        decompressOutputLength = uncompressedLength;
        decompressOutputArray = new byte[uncompressedLength];
        this.decompressOutput = decompressOutputArray;

        decompressBuf = Unpooled.wrappedBuffer(decompressOutputArray); // so we can read via kryo
    }
    inputBuf = decompressBuf;

    // LZ4 decompress, requires the size of the ORIGINAL length (because we use the FAST decompressor)
    decompressor.decompress(inputArray, inputOffset, decompressOutputArray, 0, uncompressedLength);

    inputBuf.setIndex(0, uncompressedLength);

    // read the object from the buffer.
    reader.setBuffer(inputBuf);

    return readClassAndObject(reader); // this properly sets the readerIndex, but only if it's the correct buffer
}

From source file:dorkbox.network.connection.KryoExtra.java

License:Apache License

public synchronized void writeCrypto(final Connection_ connection, final ByteBuf buffer, final Object message)
        throws IOException {
    // required by RMI and some serializers to determine which connection wrote (or has info about) this object
    this.rmiSupport = connection.rmiSupport();

    ByteBuf objectOutputBuffer = this.tempBuffer;
    objectOutputBuffer.clear(); // always have to reset everything

    // write the object to a TEMP buffer! this will be compressed
    writer.setBuffer(objectOutputBuffer);

    writeClassAndObject(writer, message);

    // save off how much data the object took
    int length = objectOutputBuffer.writerIndex();

    // NOTE: compression and encryption MUST work with byte[] because they use JNI!
    // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use
    // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it...
    // see:   https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf

    byte[] inputArray;
    int inputOffset;

    // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because
    // the buffer might be a slice of other buffer or a pooled buffer:
    //noinspection Duplicates
    if (objectOutputBuffer.hasArray() && objectOutputBuffer.array()[0] == objectOutputBuffer.getByte(0)
            && objectOutputBuffer.array().length == objectOutputBuffer.capacity()) {

        // we can use it...
        inputArray = objectOutputBuffer.array();
        inputArrayLength = -1; // this is so we don't REUSE this array accidentally!
        inputOffset = objectOutputBuffer.arrayOffset();
    } else {/*from  w  w w.  j  a va  2 s  .co  m*/
        // we can NOT use it.
        if (length > inputArrayLength) {
            inputArrayLength = length;
            inputArray = new byte[length];
            this.inputArray = inputArray;
        } else {
            inputArray = this.inputArray;
        }

        objectOutputBuffer.getBytes(objectOutputBuffer.readerIndex(), inputArray, 0, length);
        inputOffset = 0;
    }

    ////////// compressing data
    // we ALWAYS compress our data stream -- because of how AES-GCM pads data out, the small input (that would result in a larger
    // output), will be negated by the increase in size by the encryption

    byte[] compressOutput = this.compressOutput;

    int maxLengthLengthOffset = 4; // length is never negative, so 4 is OK (5 means it's negative)
    int maxCompressedLength = compressor.maxCompressedLength(length);

    // add 4 so there is room to write the compressed size to the buffer
    int maxCompressedLengthWithOffset = maxCompressedLength + maxLengthLengthOffset;

    // lazy initialize the compression output buffer
    if (maxCompressedLengthWithOffset > compressOutputLength) {
        compressOutputLength = maxCompressedLengthWithOffset;
        compressOutput = new byte[maxCompressedLengthWithOffset];
        this.compressOutput = compressOutput;
    }

    // LZ4 compress. output offset max 4 bytes to leave room for length of tempOutput data
    int compressedLength = compressor.compress(inputArray, inputOffset, length, compressOutput,
            maxLengthLengthOffset, maxCompressedLength);

    // bytes can now be written to, because our compressed data is stored in a temp array.

    final int lengthLength = OptimizeUtilsByteArray.intLength(length, true);

    // correct input.  compression output is now encryption input
    inputArray = compressOutput;
    inputOffset = maxLengthLengthOffset - lengthLength;

    // now write the ORIGINAL (uncompressed) length to the front of the byte array. This is so we can use the FAST decompress version
    OptimizeUtilsByteArray.writeInt(inputArray, length, true, inputOffset);

    // correct length for encryption
    length = compressedLength + lengthLength; // +1 to +4 for the uncompressed size bytes

    /////// encrypting data.
    final long nextGcmSequence = connection.getNextGcmSequence();

    // this is a threadlocal, so that we don't clobber other threads that are performing crypto on the same connection at the same time
    final ParametersWithIV cryptoParameters = connection.getCryptoParameters();
    BigEndian.Long_.toBytes(nextGcmSequence, cryptoParameters.getIV(), 4); // put our counter into the IV

    final GCMBlockCipher aes = this.aesEngine;
    aes.reset();
    aes.init(true, cryptoParameters);

    byte[] cryptoOutput;

    // lazy initialize the crypto output buffer
    int cryptoSize = length + 16; // from:  aes.getOutputSize(length);

    // 'output' is the temp byte array
    if (cryptoSize > cryptoOutputLength) {
        cryptoOutputLength = cryptoSize;
        cryptoOutput = new byte[cryptoSize];
        this.cryptoOutput = cryptoOutput;
    } else {
        cryptoOutput = this.cryptoOutput;
    }

    int encryptedLength = aes.processBytes(inputArray, inputOffset, length, cryptoOutput, 0);

    try {
        // authentication tag for GCM
        encryptedLength += aes.doFinal(cryptoOutput, encryptedLength);
    } catch (Exception e) {
        throw new IOException("Unable to AES encrypt the data", e);
    }

    // write out our GCM counter
    OptimizeUtilsByteBuf.writeLong(buffer, nextGcmSequence, true);

    // have to copy over the orig data, because we used the temp buffer
    buffer.writeBytes(cryptoOutput, 0, encryptedLength);
}

From source file:dorkbox.network.connection.KryoExtra.java

License:Apache License

public Object readCrypto(final Connection_ connection, final ByteBuf buffer, int length) throws IOException {
    // required by RMI and some serializers to determine which connection wrote (or has info about) this object
    this.rmiSupport = connection.rmiSupport();

    ////////////////
    // Note: we CANNOT write BACK to the buffer as "temp" storage, since there could be additional data on it!
    ////////////////

    ByteBuf inputBuf = buffer;

    final long gcmIVCounter = OptimizeUtilsByteBuf.readLong(buffer, true);
    int lengthLength = OptimizeUtilsByteArray.longLength(gcmIVCounter, true);

    // have to adjust for the gcmIVCounter
    length = length - lengthLength;/*from w  w  w .j  a va  2 s  . co m*/

    /////////// decrypting data

    // NOTE: compression and encryption MUST work with byte[] because they use JNI!
    // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use
    // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it...
    // see:   https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf

    byte[] inputArray;
    int inputOffset;

    // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because
    // the buffer might be a slice of other buffer or a pooled buffer:
    //noinspection Duplicates
    if (inputBuf.hasArray() && inputBuf.array()[0] == inputBuf.getByte(0)
            && inputBuf.array().length == inputBuf.capacity()) {

        // we can use it...
        inputArray = inputBuf.array();
        inputArrayLength = -1; // this is so we don't REUSE this array accidentally!
        inputOffset = inputBuf.arrayOffset() + lengthLength;
    } else {
        // we can NOT use it.
        if (length > inputArrayLength) {
            inputArrayLength = length;
            inputArray = new byte[length];
            this.inputArray = inputArray;
        } else {
            inputArray = this.inputArray;
        }

        inputBuf.getBytes(inputBuf.readerIndex(), inputArray, 0, length);
        inputOffset = 0;
    }

    // have to make sure to set the position of the buffer, since our conversion to array DOES NOT set the new reader index.
    buffer.readerIndex(buffer.readerIndex() + length);

    // this is a threadlocal, so that we don't clobber other threads that are performing crypto on the same connection at the same time
    final ParametersWithIV cryptoParameters = connection.getCryptoParameters();
    BigEndian.Long_.toBytes(gcmIVCounter, cryptoParameters.getIV(), 4); // put our counter into the IV

    final GCMBlockCipher aes = this.aesEngine;
    aes.reset();
    aes.init(false, cryptoParameters);

    int cryptoSize = length - 16; // from:  aes.getOutputSize(length);

    // lazy initialize the decrypt output buffer
    byte[] decryptOutputArray;
    if (cryptoSize > decryptOutputLength) {
        decryptOutputLength = cryptoSize;
        decryptOutputArray = new byte[cryptoSize];
        this.decryptOutput = decryptOutputArray;

        decryptBuf = Unpooled.wrappedBuffer(decryptOutputArray);
    } else {
        decryptOutputArray = this.decryptOutput;
    }

    int decryptedLength = aes.processBytes(inputArray, inputOffset, length, decryptOutputArray, 0);

    try {
        // authentication tag for GCM
        decryptedLength += aes.doFinal(decryptOutputArray, decryptedLength);
    } catch (Exception e) {
        throw new IOException("Unable to AES decrypt the data", e);
    }

    ///////// decompress data -- as it's ALWAYS compressed

    // get the decompressed length (at the beginning of the array)
    inputArray = decryptOutputArray;
    final int uncompressedLength = OptimizeUtilsByteArray.readInt(inputArray, true);
    inputOffset = OptimizeUtilsByteArray.intLength(uncompressedLength, true); // because 1-4 bytes for the decompressed size

    byte[] decompressOutputArray = this.decompressOutput;
    if (uncompressedLength > decompressOutputLength) {
        decompressOutputLength = uncompressedLength;
        decompressOutputArray = new byte[uncompressedLength];
        this.decompressOutput = decompressOutputArray;

        decompressBuf = Unpooled.wrappedBuffer(decompressOutputArray); // so we can read via kryo
    }
    inputBuf = decompressBuf;

    // LZ4 decompress, requires the size of the ORIGINAL length (because we use the FAST decompressor
    decompressor.decompress(inputArray, inputOffset, decompressOutputArray, 0, uncompressedLength);

    inputBuf.setIndex(0, uncompressedLength);

    // read the object from the buffer.
    reader.setBuffer(inputBuf);

    return readClassAndObject(reader); // this properly sets the readerIndex, but only if it's the correct buffer
}

From source file:dorkbox.network.pipeline.ByteBufInput.java

License:Apache License

public final void setBuffer(ByteBuf byteBuf) {
    this.byteBuf = byteBuf;

    if (byteBuf != null) {
        startIndex = byteBuf.readerIndex(); // where the object starts...
    } else {/*  ww w.  ja v  a  2 s . c om*/
        startIndex = 0;
    }
}

From source file:dorkbox.network.pipeline.ByteBufInput.java

License:Apache License

/**
 * Returns true if enough bytes are available to read an int with {@link #readInt(boolean)}.
 *//*from www .j a va2  s .  c  o  m*/
@Override
public boolean canReadInt() throws KryoException {
    ByteBuf buffer = byteBuf;
    int limit = buffer.writerIndex();

    if (limit - buffer.readerIndex() >= 5) {
        return true;
    }

    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    return true;
}

From source file:dorkbox.network.pipeline.ByteBufInput.java

License:Apache License

/**
 * Returns true if enough bytes are available to read a long with {@link #readLong(boolean)}.
 *//*from w w w. ja va 2 s .  c o  m*/
@Override
public boolean canReadLong() throws KryoException {
    ByteBuf buffer = byteBuf;
    int limit = buffer.writerIndex();

    if (limit - buffer.readerIndex() >= 9) {
        return true;
    }

    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    if ((buffer.readByte() & 0x80) == 0) {
        return true;
    }
    if (buffer.readerIndex() == limit) {
        return false;
    }
    return true;
}

From source file:dorkbox.network.pipeline.ByteBufInput.java

License:Apache License

private String readAscii() {
    ByteBuf buffer = byteBuf;

    int start = buffer.readerIndex() - 1;
    int b;/*from  w ww  .  j  a va2  s.  c om*/
    do {
        b = buffer.readByte();
    } while ((b & 0x80) == 0);
    int i = buffer.readerIndex() - 1;
    buffer.setByte(i, buffer.getByte(i) & 0x7F); // Mask end of ascii bit.

    int capp = buffer.readerIndex() - start;

    byte[] ba = new byte[capp];
    buffer.getBytes(start, ba);

    @SuppressWarnings("deprecation")
    String value = new String(ba, 0, 0, capp);

    buffer.setByte(i, buffer.getByte(i) | 0x80);
    return value;
}