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.digitalpetri.opcua.stack.core.channel.messages.TcpMessageDecoder.java

License:Apache License

public static HelloMessage decodeHello(ByteBuf buffer) throws UaException {
    MessageType messageType = MessageType.fromMediumInt(buffer.readMedium());
    char chunkType = (char) buffer.readByte();
    buffer.skipBytes(4); // length

    assert (messageType == MessageType.Hello && chunkType == 'F');

    return HelloMessage.decode(buffer);
}

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

License:Apache License

public static AcknowledgeMessage decodeAcknowledge(ByteBuf buffer) throws UaException {
    MessageType messageType = MessageType.fromMediumInt(buffer.readMedium());
    char chunkType = (char) buffer.readByte();
    buffer.skipBytes(4); // length

    assert (messageType == MessageType.Acknowledge && chunkType == 'F');

    return AcknowledgeMessage.decode(buffer);
}

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

License:Apache License

public static ErrorMessage decodeError(ByteBuf buffer) throws UaException {
    MessageType messageType = MessageType.fromMediumInt(buffer.readMedium());
    char chunkType = (char) buffer.readByte();
    buffer.skipBytes(4); // length

    assert (messageType == MessageType.Error && chunkType == 'F');

    return ErrorMessage.decode(buffer);
}

From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.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 OpenSecureChannel:
            onOpenSecureChannel(ctx, buffer.readSlice(messageLength));
            break;

        case CloseSecureChannel:
            logger.debug("Received CloseSecureChannelRequest");
            if (secureChannel != null) {
                server.closeSecureChannel(secureChannel);
            }/*from   w ww  .  jav  a  2s .  c o  m*/
            buffer.skipBytes(messageLength);
            break;

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

From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.java

License:Apache License

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3); // Skip messageType

    char chunkType = (char) buffer.readByte();

    if (chunkType == 'A') {
        chunkBuffers.forEach(ByteBuf::release);
        chunkBuffers.clear();// w w w  . j a v a 2s .  c o  m
        headerRef.set(null);
    } else {
        buffer.skipBytes(4); // Skip messageSize

        long secureChannelId = buffer.readUnsignedInt();
        AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer);

        if (secureChannelId == 0) {
            // Okay, this is the first OpenSecureChannelRequest... carry on.
            String endpointUrl = ctx.channel().attr(UaTcpServerHelloHandler.ENDPOINT_URL_KEY).get();
            String securityPolicyUri = securityHeader.getSecurityPolicyUri();

            EndpointDescription endpointDescription = Arrays.stream(server.getEndpointDescriptions())
                    .filter(e -> {
                        String s1 = pathOrUrl(endpointUrl);
                        String s2 = pathOrUrl(e.getEndpointUrl());
                        boolean uriMatch = s1.equals(s2);
                        boolean policyMatch = e.getSecurityPolicyUri().equals(securityPolicyUri);
                        return uriMatch && policyMatch;
                    }).findFirst().orElse(null);

            if (endpointDescription == null && !server.getConfig().isStrictEndpointUrlsEnabled()) {
                endpointDescription = Arrays.stream(server.getEndpointDescriptions())
                        .filter(e -> e.getSecurityPolicyUri().equals(securityPolicyUri)).findFirst()
                        .orElse(null);
            }

            if (endpointDescription == null) {
                throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "SecurityPolicy URI did not match");
            }

            secureChannel = server.openSecureChannel();
            secureChannel.setEndpointDescription(endpointDescription);
        } else {
            secureChannel = server.getSecureChannel(secureChannelId);

            if (secureChannel == null) {
                throw new UaException(StatusCodes.Bad_TcpSecureChannelUnknown,
                        "unknown secure channel id: " + secureChannelId);
            }

            if (!secureChannel.getRemoteCertificateBytes().equals(securityHeader.getSenderCertificate())) {
                throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                        "certificate requesting renewal did not match existing certificate.");
            }

            Channel boundChannel = secureChannel.attr(UaTcpStackServer.BoundChannelKey).get();
            if (boundChannel != null && boundChannel != ctx.channel()) {
                throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                        "received a renewal request from channel other than the bound channel.");
            }
        }

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

        SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityHeader.getSecurityPolicyUri());
        secureChannel.setSecurityPolicy(securityPolicy);

        if (!securityHeader.getSenderCertificate().isNull() && securityPolicy != SecurityPolicy.None) {
            secureChannel.setRemoteCertificate(securityHeader.getSenderCertificate().bytes());

            try {
                CertificateValidator certificateValidator = server.getCertificateValidator();

                certificateValidator.validate(secureChannel.getRemoteCertificate());

                certificateValidator.verifyTrustChain(secureChannel.getRemoteCertificate(),
                        secureChannel.getRemoteCertificateChain());
            } catch (UaException e) {
                try {
                    UaException cause = new UaException(e.getStatusCode(), "security checks failed");
                    ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause);

                    logger.debug("[remote={}] {}.", ctx.channel().remoteAddress(), errorMessage.getReason(),
                            cause);
                } catch (Exception ignored) {
                }
            }
        }

        if (!securityHeader.getReceiverThumbprint().isNull()) {
            CertificateManager certificateManager = server.getCertificateManager();

            Optional<X509Certificate> localCertificate = certificateManager
                    .getCertificate(securityHeader.getReceiverThumbprint());

            Optional<KeyPair> keyPair = certificateManager.getKeyPair(securityHeader.getReceiverThumbprint());

            if (localCertificate.isPresent() && keyPair.isPresent()) {
                secureChannel.setLocalCertificate(localCertificate.get());
                secureChannel.setKeyPair(keyPair.get());
            } else {
                throw new UaException(StatusCodes.Bad_SecurityChecksFailed,
                        "no certificate for provided thumbprint");
            }
        }

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

        if (chunkType == 'F') {
            final List<ByteBuf> buffersToDecode = chunkBuffers;

            chunkBuffers = new ArrayList<>(maxChunkCount);
            headerRef.set(null);

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

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

                    OpenSecureChannelRequest request = binaryDecoder.setBuffer(messageBuffer)
                            .decodeMessage(null);

                    logger.debug("Received OpenSecureChannelRequest ({}, id={}).", request.getRequestType(),
                            secureChannelId);

                    long requestId = chunkDecoder.getLastRequestId();
                    installSecurityToken(ctx, request, requestId);
                } catch (UaException e) {
                    logger.error("Error decoding asymmetric message: {}", e.getMessage(), e);
                    ctx.close();
                } finally {
                    if (messageBuffer != null) {
                        messageBuffer.release();
                    }
                    buffersToDecode.clear();
                }
            });
        }
    }
}

From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerSymmetricHandler.java

License:Apache License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws UaException {
    buffer.skipBytes(3); // Skip messageType

    char chunkType = (char) buffer.readByte();

    if (chunkType == 'A') {
        chunkBuffers.forEach(ByteBuf::release);
        chunkBuffers.clear();//from w w  w. ja v a 2  s.  com
    } else {
        buffer.skipBytes(4); // Skip messageSize

        long secureChannelId = buffer.readUnsignedInt();
        if (secureChannelId != secureChannel.getChannelId()) {
            throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                    "invalid secure channel id: " + secureChannelId);
        }

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

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

            serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
                try {
                    validateChunkHeaders(buffersToDecode);

                    ByteBuf messageBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode);

                    binaryDecoder.setBuffer(messageBuffer);
                    UaRequestMessage request = binaryDecoder.decodeMessage(null);

                    ServiceRequest<UaRequestMessage, UaResponseMessage> serviceRequest = new ServiceRequest<>(
                            request, chunkDecoder.getLastRequestId(), server, secureChannel);

                    server.getExecutorService().execute(() -> server.receiveRequest(serviceRequest));

                    messageBuffer.release();
                    buffersToDecode.clear();
                } catch (UaException e) {
                    logger.error("Error decoding symmetric message: {}", e.getMessage(), e);
                    ctx.close();
                }
            });
        }
    }
}

From source file:com.eightkdata.mongowp.bson.netty.PooledNettyStringReader.java

License:Open Source License

@Override
/**/*from  www  . j a v a 2s  . co  m*/
 * A method that skips a C-string from a ByteBuf. This method modified the internal state of the
 * ByteBuf, advancing the read pointer to the position after the cstring.
 *
 * @param buffer
 * @throws com.eightkdata.mongowp.bson.netty.NettyBsonReaderException
 */
public void skipCString(ByteBuf buffer) throws NettyBsonReaderException {
    int bytesBefore = buffer.bytesBefore(CSTRING_BYTE_TERMINATION);
    if (bytesBefore == -1) {
        throw new NettyBsonReaderException("A cstring was expected but no 0x00 byte was found");
    }
    buffer.skipBytes(bytesBefore + 1);
}

From source file:com.eightkdata.mongowp.bson.netty.PooledNettyStringReader.java

License:Open Source License

@Override
public String readString(@Loose @ModifiesIndexes ByteBuf byteBuf, boolean likelyCacheable) {
    int stringLength = byteBuf.readInt();

    String str = stringPool.fromPool(likelyCacheable, byteBuf.slice(byteBuf.readerIndex(), stringLength - 1));

    byteBuf.skipBytes(stringLength);

    return str;/*  ww w  . j a  v  a2 s .com*/
}

From source file:com.eightkdata.mongowp.mongoserver.decoder.DeleteMessageDecoder.java

License:Open Source License

@Override
public @Nonnegative DeleteMessage decode(ByteBuf buffer, RequestBaseMessage requestBaseMessage)
        throws InvalidMessageException {
    buffer.skipBytes(4);
    String fullCollectionName = ByteBufUtil.readCString(buffer);
    int flags = buffer.readInt();
    BSONDocument document = new MongoBSONDocument(buffer);

    return new DeleteMessage(requestBaseMessage, flags, fullCollectionName, document);
}

From source file:com.eightkdata.mongowp.mongoserver.decoder.GetMoreMessageDecoder.java

License:Open Source License

@Override
public @Nonnegative GetMoreMessage decode(ByteBuf buffer, RequestBaseMessage requestBaseMessage)
        throws InvalidMessageException {
    buffer.skipBytes(4);
    String fullCollectionName = ByteBufUtil.readCString(buffer);
    int numberToReturn = buffer.readInt();
    long cursorId = buffer.readLong();

    return new GetMoreMessage(requestBaseMessage, fullCollectionName, numberToReturn, cursorId);
}