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:com.dempe.chat.common.mqtt.codec.UnsubscribeDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();/*www .  j  a va2 s.c  o m*/
    UnsubscribeMessage message = new UnsubscribeMessage();
    if (!decodeCommonHeader(message, 0x02, in)) {
        in.resetReaderIndex();
        return;
    }

    //check qos level
    if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) {
        throw new CorruptedFrameException(
                "Found an Unsubscribe message with qos other than LEAST_ONE, was: " + message.getQos());
    }

    int start = in.readerIndex();
    //read  messageIDs
    message.setMessageID(in.readUnsignedShort());
    int read = in.readerIndex() - start;
    while (read < message.getRemainingLength()) {
        String topicFilter = Utils.decodeString(in);
        //check topic is at least one char [MQTT-4.7.3-1]
        if (topicFilter.length() == 0) {
            throw new CorruptedFrameException("Received an UNSUBSCRIBE with empty topic filter");
        }
        message.addTopicFilter(topicFilter);
        read = in.readerIndex() - start;
    }
    if (message.topicFilters().isEmpty()) {
        throw new CorruptedFrameException("unsubscribe MUST have got at least 1 topic");
    }
    out.add(message);
}

From source file:com.difference.historybook.proxy.littleproxy.LittleProxyResponse.java

License:Apache License

@Override
public byte[] getContent() {
    ByteBuf buf = response.content();
    byte[] bytes;
    int length = buf.readableBytes();

    if (buf.hasArray()) {
        bytes = buf.array();//from  w  w w.ja  v  a2  s.c om
    } else {
        bytes = new byte[length];
        buf.getBytes(buf.readerIndex(), bytes);
    }
    buf.release();
    return bytes;
}

From source file:com.digitalpetri.modbus.codec.ModbusTcpCodec.java

License:Apache License

public void decode(ByteBuf buffer, List<Object> out) throws Exception {
    int startIndex = buffer.readerIndex();

    while (buffer.readableBytes() >= HeaderLength
            && buffer.readableBytes() >= getLength(buffer, startIndex) + HeaderSize) {

        try {//from ww w.j a  v  a  2 s.  com
            MbapHeader mbapHeader = MbapHeader.decode(buffer);
            ModbusPdu modbusPdu = decoder.decode(buffer);

            if (modbusPdu instanceof UnsupportedPdu) {
                // Advance past any bytes we should have read but didn't...
                int endIndex = startIndex + getLength(buffer, startIndex) + 6;
                buffer.readerIndex(endIndex);
            }

            out.add(new ModbusTcpPayload(mbapHeader.getTransactionId(), mbapHeader.getUnitId(), modbusPdu));
        } catch (Throwable t) {
            throw new Exception("error decoding header/pdu", t);
        }

        startIndex = buffer.readerIndex();
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAcknowledgeHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    while (buffer.readableBytes() >= HEADER_LENGTH && buffer.readableBytes() >= getMessageLength(buffer)) {

        int messageLength = getMessageLength(buffer);
        MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

        switch (messageType) {
        case Acknowledge:
            onAcknowledge(ctx, buffer.readSlice(messageLength));
            break;

        case Error:
            onError(ctx, buffer.readSlice(messageLength));
            break;

        default:/*from ww  w .ja  v a2  s .  c  o m*/
            out.add(buffer.readSlice(messageLength).retain());
        }
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    while (buffer.readableBytes() >= HEADER_LENGTH && buffer.readableBytes() >= getMessageLength(buffer)) {

        int messageLength = getMessageLength(buffer);
        MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

        switch (messageType) {
        case OpenSecureChannel:
            onOpenSecureChannel(ctx, buffer.readSlice(messageLength));
            break;

        case Error:
            onError(ctx, buffer.readSlice(messageLength));
            break;

        default://from  w w w . j  ava  2s. c o  m
            throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid,
                    "unexpected MessageType: " + messageType);
        }
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

private void decodeMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    int messageLength = getMessageLength(buffer);
    MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

    switch (messageType) {
    case OpenSecureChannel:
        onOpenSecureChannel(ctx, buffer.readSlice(messageLength));
        break;//from w  w w.java  2 s  . c  o  m

    case SecureMessage:
        onSecureMessage(ctx, buffer.readSlice(messageLength));
        break;

    case Error:
        onError(ctx, buffer.readSlice(messageLength));
        break;

    default:
        throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid, "unexpected MessageType: " + messageType);
    }
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    while (buffer.readableBytes() >= HEADER_LENGTH && buffer.readableBytes() >= getMessageLength(buffer)) {

        int messageLength = getMessageLength(buffer);
        MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

        switch (messageType) {
        case SecureMessage:
            onSecureMessage(ctx, buffer.readSlice(messageLength));
            break;

        case Error:
            onError(ctx, buffer.readSlice(messageLength));
            break;

        default://w  w  w. j a va  2s  .c o m
            out.add(buffer.readSlice(messageLength).retain());
        }
    }
}

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);
        }/* w w w. j ava2 s  .  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);
}

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

License:Apache License

private void decryptChunk(Delegate delegate, SecureChannel channel, ByteBuf chunkBuffer) throws UaException {
    int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel);
    int blockCount = chunkBuffer.readableBytes() / cipherTextBlockSize;

    int plainTextBufferSize = cipherTextBlockSize * blockCount;

    ByteBuf plainTextBuffer = BufferUtil.buffer(plainTextBufferSize);

    ByteBuffer plainTextNioBuffer = plainTextBuffer.writerIndex(plainTextBufferSize).nioBuffer();

    ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer();

    try {//  w ww. ja  va  2 s . com
        Cipher cipher = delegate.getCipher(channel);

        assert (chunkBuffer.readableBytes() % cipherTextBlockSize == 0);

        if (delegate instanceof AsymmetricDelegate) {
            for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) {
                chunkNioBuffer.limit(chunkNioBuffer.position() + cipherTextBlockSize);

                cipher.doFinal(chunkNioBuffer, plainTextNioBuffer);
            }
        } else {
            cipher.doFinal(chunkNioBuffer, plainTextNioBuffer);
        }
    } catch (GeneralSecurityException e) {
        throw new UaException(StatusCodes.Bad_SecurityChecksFailed, e);
    }

    /* Write plainTextBuffer back into the chunk buffer we decrypted from. */
    plainTextNioBuffer.flip(); // limit = pos, pos = 0

    chunkBuffer.writerIndex(chunkBuffer.readerIndex());
    chunkBuffer.writeBytes(plainTextNioBuffer);

    plainTextBuffer.release();
}

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

License:Apache License

/**
 * Get the message length from a {@link ByteBuf} containing a {@link TcpMessageEncoder}. The reader index will not be
 * advanced.// ww w .  java  2s  .  co m
 *
 * @param buffer {@link ByteBuf} to extract from.
 * @return The message length, which includes the size of the header.
 */
default int getMessageLength(ByteBuf buffer) {
    return Ints.checkedCast(buffer.getUnsignedInt(buffer.readerIndex() + HEADER_LENGTH_INDEX));
}