Example usage for io.netty.buffer CompositeByteBuf order

List of usage examples for io.netty.buffer CompositeByteBuf order

Introduction

In this page you can find the example usage for io.netty.buffer CompositeByteBuf order.

Prototype

@Override
    public ByteBuf order(ByteOrder endianness) 

Source Link

Usage

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

License:Apache License

private ByteBuf decode(Delegate delegate, SecureChannel channel, List<ByteBuf> chunkBuffers)
        throws UaException {
    CompositeByteBuf composite = BufferUtil.compositeBuffer();

    int signatureSize = delegate.getSignatureSize(channel);
    int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel);

    boolean encrypted = delegate.isEncryptionEnabled(channel);
    boolean signed = delegate.isSigningEnabled(channel);

    for (ByteBuf chunkBuffer : chunkBuffers) {
        char chunkType = (char) chunkBuffer.getByte(3);

        chunkBuffer.skipBytes(SecureMessageHeader.SECURE_MESSAGE_HEADER_SIZE);

        delegate.readSecurityHeader(channel, chunkBuffer);

        if (encrypted) {
            decryptChunk(delegate, channel, chunkBuffer);
        }//from w  w  w .  j a  v  a 2s.c o m

        int encryptedStart = chunkBuffer.readerIndex();
        chunkBuffer.readerIndex(0);

        if (signed) {
            delegate.verifyChunk(channel, chunkBuffer);
        }

        int paddingSize = encrypted ? getPaddingSize(cipherTextBlockSize, signatureSize, chunkBuffer) : 0;
        int bodyEnd = chunkBuffer.readableBytes() - signatureSize - paddingSize;

        chunkBuffer.readerIndex(encryptedStart);

        SequenceHeader sequenceHeader = SequenceHeader.decode(chunkBuffer);
        long sequenceNumber = sequenceHeader.getSequenceNumber();
        lastRequestId = sequenceHeader.getRequestId();

        if (lastSequenceNumber == -1) {
            lastSequenceNumber = sequenceNumber;
        } else {
            if (lastSequenceNumber + 1 != sequenceNumber) {
                String message = String.format("expected sequence number %s but received %s",
                        lastSequenceNumber + 1, sequenceNumber);

                logger.error(message);
                logger.error(ByteBufUtil.hexDump(chunkBuffer, 0, chunkBuffer.writerIndex()));

                throw new UaException(StatusCodes.Bad_SecurityChecksFailed, message);
            }

            lastSequenceNumber = sequenceNumber;
        }

        ByteBuf bodyBuffer = chunkBuffer.readSlice(bodyEnd - chunkBuffer.readerIndex());

        if (chunkType == 'A') {
            ErrorMessage errorMessage = ErrorMessage.decode(bodyBuffer);

            throw new MessageAbortedException(errorMessage.getError(), errorMessage.getReason());
        }

        composite.addComponent(bodyBuffer);
        composite.writerIndex(composite.writerIndex() + bodyBuffer.readableBytes());
    }

    return composite.order(ByteOrder.LITTLE_ENDIAN);
}