Example usage for io.netty.buffer ByteBuf skipBytes

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

Introduction

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

Prototype

public abstract ByteBuf skipBytes(int length);

Source Link

Document

Increases the current readerIndex by the specified length in this buffer.

Usage

From source file:com.cloudhopper.smpp.transcoder.DefaultPduTranscoder.java

License:Apache License

protected Pdu doDecode(int commandLength, ByteBuf buffer)
        throws UnrecoverablePduException, RecoverablePduException {
    // skip the length field because we already parsed it
    buffer.skipBytes(SmppConstants.PDU_INT_LENGTH);

    // read the remaining portion of the PDU header
    int commandId = buffer.readInt();
    int commandStatus = buffer.readInt();
    int sequenceNumber = buffer.readInt();

    // this is a major issue if the sequence number is invalid
    SequenceNumber.assertValid(sequenceNumber);

    Pdu pdu = null;/*from w w w .  ja  va2  s.c o m*/

    // any command id with its 31st bit set to true is a response
    if (PduUtil.isRequestCommandId(commandId)) {
        if (commandId == SmppConstants.CMD_ID_ENQUIRE_LINK) {
            pdu = new EnquireLink();
        } else if (commandId == SmppConstants.CMD_ID_DELIVER_SM) {
            pdu = new DeliverSm();
        } else if (commandId == SmppConstants.CMD_ID_SUBMIT_SM) {
            pdu = new SubmitSm();
        } else if (commandId == SmppConstants.CMD_ID_DATA_SM) {
            pdu = new DataSm();
        } else if (commandId == SmppConstants.CMD_ID_CANCEL_SM) {
            pdu = new CancelSm();
        } else if (commandId == SmppConstants.CMD_ID_QUERY_SM) {
            pdu = new QuerySm();
        } else if (commandId == SmppConstants.CMD_ID_BIND_TRANSCEIVER) {
            pdu = new BindTransceiver();
        } else if (commandId == SmppConstants.CMD_ID_BIND_TRANSMITTER) {
            pdu = new BindTransmitter();
        } else if (commandId == SmppConstants.CMD_ID_BIND_RECEIVER) {
            pdu = new BindReceiver();
        } else if (commandId == SmppConstants.CMD_ID_UNBIND) {
            pdu = new Unbind();
        } else {
            pdu = new PartialPdu(commandId);
        }
    } else {
        if (commandId == SmppConstants.CMD_ID_SUBMIT_SM_RESP) {
            pdu = new SubmitSmResp();
        } else if (commandId == SmppConstants.CMD_ID_DELIVER_SM_RESP) {
            pdu = new DeliverSmResp();
        } else if (commandId == SmppConstants.CMD_ID_DATA_SM_RESP) {
            pdu = new DataSmResp();
        } else if (commandId == SmppConstants.CMD_ID_CANCEL_SM_RESP) {
            pdu = new CancelSmResp();
        } else if (commandId == SmppConstants.CMD_ID_QUERY_SM_RESP) {
            pdu = new QuerySmResp();
        } else if (commandId == SmppConstants.CMD_ID_ENQUIRE_LINK_RESP) {
            pdu = new EnquireLinkResp();
        } else if (commandId == SmppConstants.CMD_ID_BIND_TRANSCEIVER_RESP) {
            pdu = new BindTransceiverResp();
        } else if (commandId == SmppConstants.CMD_ID_BIND_RECEIVER_RESP) {
            pdu = new BindReceiverResp();
        } else if (commandId == SmppConstants.CMD_ID_BIND_TRANSMITTER_RESP) {
            pdu = new BindTransmitterResp();
        } else if (commandId == SmppConstants.CMD_ID_UNBIND_RESP) {
            pdu = new UnbindResp();
        } else if (commandId == SmppConstants.CMD_ID_GENERIC_NACK) {
            pdu = new GenericNack();
        } else {
            pdu = new PartialPduResp(commandId);
        }
    }

    // set pdu header values
    pdu.setCommandLength(commandLength);
    pdu.setCommandStatus(commandStatus);
    pdu.setSequenceNumber(sequenceNumber);

    // check if we need to throw an exception
    if (pdu instanceof PartialPdu) {
        throw new UnknownCommandIdException(pdu,
                "Unsupported or unknown PDU request commandId [0x" + HexUtil.toHexString(commandId) + "]");
    } else if (pdu instanceof PartialPduResp) {
        throw new UnknownCommandIdException(pdu,
                "Unsupported or unknown PDU response commandId [0x" + HexUtil.toHexString(commandId) + "]");
    }

    // see if we can map the command status into a message
    if (pdu instanceof PduResponse) {
        PduResponse response = (PduResponse) pdu;
        response.setResultMessage(context.lookupResultMessage(commandStatus));
    }

    try {
        // parse pdu body parameters (may throw exception)
        pdu.readBody(buffer);
        // parse pdu optional parameters (may throw exception)
        pdu.readOptionalParameters(buffer, context);
    } catch (RecoverablePduException e) {
        // check if we should add the partial pdu to the exception
        if (e.getPartialPdu() == null) {
            e.setPartialPdu(pdu);
        }
        // rethrow it
        throw e;
    }

    return pdu;
}

From source file:com.couchbase.client.core.endpoint.util.ByteBufJsonHelperTest.java

License:Apache License

/**
 * See JVMCBC-239./*from w w w .  j av  a 2 s. com*/
 */
@Test
public void testFindNextCharNotPrefixedByAfterReaderIndexMoved() throws Exception {
    //before JVMCBC-239 the fact that the head of the buffer, with skipped data, is larger than its tail would
    //cause an negative search length and the method would return a -1.
    ByteBuf source = Unpooled.copiedBuffer("sectionWithLotsAndLotsOfDataToSkip\": \"123456\\\"78901234567890\"",
            CharsetUtil.UTF_8);
    source.skipBytes(38);

    assertEquals(22, ByteBufJsonHelper.findNextCharNotPrefixedBy(source, '"', '\\'));
}

From source file:com.dempe.chat.common.mqtt.codec.Utils.java

License:Open Source License

static boolean checkHeaderAvailability(ByteBuf in) {
    if (in.readableBytes() < 1) {
        return false;
    }/*from w ww .j  av a2  s .c o m*/
    //byte h1 = in.get();
    //byte messageType = (byte) ((h1 & 0x00F0) >> 4);
    in.skipBytes(1); //skip the messageType byte

    int remainingLength = Utils.decodeRemainingLenght(in);
    if (remainingLength == -1) {
        return false;
    }

    //check remaining length
    if (in.readableBytes() < remainingLength) {
        return false;
    }

    //return messageType == type ? MessageDecoderResult.OK : MessageDecoderResult.NOT_OK;
    return true;
}

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

License:Apache License

private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) {
    logger.debug("Received Acknowledge message on channel={}.", ctx.channel());

    buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize

    AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer);

    long remoteProtocolVersion = acknowledge.getProtocolVersion();
    long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize();
    long remoteSendBufferSize = acknowledge.getSendBufferSize();
    long remoteMaxMessageSize = acknowledge.getMaxMessageSize();
    long remoteMaxChunkCount = acknowledge.getMaxChunkCount();

    if (PROTOCOL_VERSION > remoteProtocolVersion) {
        logger.warn("Client protocol version ({}) does not match server protocol version ({}).",
                PROTOCOL_VERSION, remoteProtocolVersion);
    }//from  w  w  w .  j  a  v a 2 s  .c om

    ChannelConfig config = client.getChannelConfig();

    /* Our receive buffer size is determined by the remote send buffer size. */
    long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize());

    /* Our send buffer size is determined by the remote receive buffer size. */
    long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize());

    /* Max message size the remote can send us; not influenced by remote configuration. */
    long localMaxMessageSize = config.getMaxMessageSize();

    /* Max chunk count the remote can send us; not influenced by remote configuration. */
    long localMaxChunkCount = config.getMaxChunkCount();

    ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize),
            Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize),
            Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize),
            Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize),
            Ints.saturatedCast(remoteMaxChunkCount));

    ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake);

    ctx.executor().execute(() -> {
        int maxArrayLength = client.getChannelConfig().getMaxArrayLength();
        int maxStringLength = client.getChannelConfig().getMaxStringLength();

        SerializationQueue serializationQueue = new SerializationQueue(client.getConfig().getExecutor(),
                parameters, maxArrayLength, maxStringLength);

        UaTcpClientAsymmetricHandler handler = new UaTcpClientAsymmetricHandler(client, serializationQueue,
                secureChannel, handshakeFuture);

        ctx.pipeline().addLast(handler);
    });
}

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

License:Apache License

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();

    secureChannel.setChannelId(secureChannelId);

    AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer);
    if (!headerRef.compareAndSet(null, securityHeader)) {
        if (!securityHeader.equals(headerRef.get())) {
            throw new UaRuntimeException(StatusCodes.Bad_SecurityChecksFailed,
                    "subsequent AsymmetricSecurityHeader did not match");
        }/*from  www . j a v a2  s . c o  m*/
    }

    int chunkSize = buffer.readerIndex(0).readableBytes();

    if (chunkSize > maxChunkSize) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk size exceeded (%s)", maxChunkSize));
    }

    chunkBuffers.add(buffer.retain());

    if (chunkBuffers.size() > maxChunkCount) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk count exceeded (%s)", maxChunkCount));
    }

    char chunkType = (char) buffer.getByte(3);

    if (chunkType == 'A' || chunkType == 'F') {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);

                UaResponseMessage responseMessage = binaryDecoder.setBuffer(decodedBuffer).decodeMessage(null);

                StatusCode serviceResult = responseMessage.getResponseHeader().getServiceResult();

                if (serviceResult.isGood()) {
                    OpenSecureChannelResponse response = (OpenSecureChannelResponse) responseMessage;

                    secureChannel.setChannelId(response.getSecurityToken().getChannelId().longValue());
                    logger.debug("Received OpenSecureChannelResponse.");

                    installSecurityToken(ctx, response);
                } else {
                    ServiceFault serviceFault = (responseMessage instanceof ServiceFault)
                            ? (ServiceFault) responseMessage
                            : new ServiceFault(responseMessage.getResponseHeader());

                    throw new UaServiceFaultException(serviceFault);
                }
            } catch (MessageAbortedException e) {
                logger.error("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());
                ctx.close();
            } catch (Throwable t) {
                logger.error("Error decoding OpenSecureChannelResponse: {}", t.getMessage(), t);
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
                buffersToDecode.clear();
            }
        });
    }
}

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

License:Apache License

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    if (secureChannelTimeout != null) {
        if (secureChannelTimeout.cancel()) {
            logger.debug("OpenSecureChannel timeout canceled");

            secureChannelTimeout = null;
        } else {//from  w  w w  . j  a va  2  s  . c  o  m
            logger.warn("timed out waiting for secure channel");

            handshakeFuture.completeExceptionally(
                    new UaException(StatusCodes.Bad_Timeout, "timed out waiting for secure channel"));
            ctx.close();
            return;
        }
    }

    buffer.skipBytes(3 + 1 + 4 + 4); // skip messageType, chunkType, messageSize, secureChannelId

    AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer);
    if (!headerRef.compareAndSet(null, securityHeader)) {
        if (!securityHeader.equals(headerRef.get())) {
            throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                    "subsequent AsymmetricSecurityHeader did not match");
        }
    }

    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = ImmutableList.copyOf(chunkBuffers);
        chunkBuffers = new LinkedList<>();

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);

                UaResponseMessage responseMessage = binaryDecoder.setBuffer(decodedBuffer).decodeMessage(null);

                StatusCode serviceResult = responseMessage.getResponseHeader().getServiceResult();

                if (serviceResult.isGood()) {
                    OpenSecureChannelResponse response = (OpenSecureChannelResponse) responseMessage;

                    secureChannel.setChannelId(response.getSecurityToken().getChannelId().longValue());
                    logger.debug("Received OpenSecureChannelResponse.");

                    installSecurityToken(ctx, response);

                    handshakeFuture.complete(secureChannel);
                } else {
                    ServiceFault serviceFault = (responseMessage instanceof ServiceFault)
                            ? (ServiceFault) responseMessage
                            : new ServiceFault(responseMessage.getResponseHeader());

                    throw new UaServiceFaultException(serviceFault);
                }
            } catch (MessageAbortedException e) {
                logger.error("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());
                ctx.close();
            } catch (Throwable t) {
                logger.error("Error decoding OpenSecureChannelResponse: {}", t.getMessage(), t);
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
            }
        });
    }
}

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

License:Apache License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();
    if (secureChannelId != secureChannel.getChannelId()) {
        throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                "invalid secure channel id: " + secureChannelId);
    }/* www .j  av  a 2s .  c om*/

    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = ImmutableList.copyOf(chunkBuffers);
        chunkBuffers = new LinkedList<>();

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode);

                binaryDecoder.setBuffer(decodedBuffer);
                UaResponseMessage response = binaryDecoder.decodeMessage(null);

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().complete(response));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (MessageAbortedException e) {
                logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (Throwable t) {
                logger.error("Error decoding symmetric message: {}", t.getMessage(), t);
                serializationQueue.pause();
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
            }
        });
    }
}

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

License:Apache License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();
    if (secureChannelId != secureChannel.getChannelId()) {
        throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                "invalid secure channel id: " + secureChannelId);
    }//  w  w  w  .j a  v a  2s.co  m

    int chunkSize = buffer.readerIndex(0).readableBytes();
    if (chunkSize > maxChunkSize) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk size exceeded (%s)", maxChunkSize));
    }

    chunkBuffers.add(buffer.retain());

    if (chunkBuffers.size() > maxChunkCount) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk count exceeded (%s)", maxChunkCount));
    }

    char chunkType = (char) buffer.getByte(3);

    if (chunkType == 'A' || chunkType == 'F') {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                validateChunkHeaders(buffersToDecode);

                decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode);

                binaryDecoder.setBuffer(decodedBuffer);
                UaResponseMessage response = binaryDecoder.decodeMessage(null);

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().complete(response));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (MessageAbortedException e) {
                logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (Throwable t) {
                logger.error("Error decoding symmetric message: {}", t.getMessage(), t);
                ctx.close();
                serializationQueue.pause();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
                buffersToDecode.clear();
            }
        });
    }
}

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

License:Apache License

private void validateChunkHeaders(List<ByteBuf> chunkBuffers) throws UaException {
    ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();
    long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue();
    long previousTokenId = channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L);

    for (ByteBuf chunkBuffer : chunkBuffers) {
        chunkBuffer.skipBytes(3 + 1 + 4 + 4); // skip messageType, chunkType, messageSize, secureChannelId

        SymmetricSecurityHeader securityHeader = SymmetricSecurityHeader.decode(chunkBuffer);

        if (securityHeader.getTokenId() != currentTokenId) {
            if (securityHeader.getTokenId() != previousTokenId) {
                String message = String.format(
                        "received unknown secure channel token. "
                                + "tokenId=%s, currentTokenId=%s, previousTokenId=%s",
                        securityHeader.getTokenId(), currentTokenId, previousTokenId);

                throw new UaException(StatusCodes.Bad_SecureChannelTokenUnknown, message);
            }/* w ww  . j  a  v  a  2  s .  c o m*/
        }

        chunkBuffer.readerIndex(0);
    }
}

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  a  v a2  s  . c om

        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);
}