Example usage for io.netty.buffer ByteBuf readUnsignedInt

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

Introduction

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

Prototype

public abstract long readUnsignedInt();

Source Link

Document

Gets an unsigned 32-bit integer at the current readerIndex and increases the readerIndex by 4 in this buffer.

Usage

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private ASPathAttribute decodeASPathAttribute(ByteBuf buffer, ASType asType) {
    ASPathAttribute attr = new ASPathAttribute(asType);

    while (buffer.isReadable()) {
        if (buffer.readableBytes() < 2)
            throw new MalformedASPathAttributeException();

        int segmentType = buffer.readUnsignedByte();
        int pathLength = buffer.readUnsignedByte();
        int pathOctetLength = (pathLength * (asType == ASType.AS_NUMBER_4OCTETS ? 4 : 2));

        if (buffer.readableBytes() < pathOctetLength)
            throw new MalformedASPathAttributeException();

        PathSegment segment = new PathSegment(asType);

        try {/*from  w w w  .j av  a 2 s. com*/
            segment.setPathSegmentType(PathSegmentTypeCodec.fromCode(segmentType));
        } catch (IllegalArgumentException e) {
            log.error("cannot convert AS_PATH type", e);

            throw new MalformedASPathAttributeException();
        }

        for (int i = 0; i < pathLength; i++) {
            if (asType == ASType.AS_NUMBER_4OCTETS)
                segment.getAses().add((int) buffer.readUnsignedInt());
            else
                segment.getAses().add(buffer.readUnsignedShort());
        }

        attr.getPathSegments().add(segment);
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private MultiExitDiscPathAttribute decodeMultiExitDiscPathAttribute(ByteBuf buffer) {
    MultiExitDiscPathAttribute attr = new MultiExitDiscPathAttribute();

    if (buffer.readableBytes() != 4)
        throw new AttributeLengthException();

    attr.setDiscriminator((int) buffer.readUnsignedInt());

    return attr;//  ww w . j a v a  2 s . c om
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private LocalPrefPathAttribute decodeLocalPrefPathAttribute(ByteBuf buffer) {
    LocalPrefPathAttribute attr = new LocalPrefPathAttribute();

    if (buffer.readableBytes() != 4)
        throw new AttributeLengthException();

    attr.setLocalPreference((int) buffer.readUnsignedInt());

    return attr;//from www  .  j  a  v  a 2s .co  m
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private AggregatorPathAttribute decodeAggregatorPathAttribute(ByteBuf buffer, ASType asType) {
    AggregatorPathAttribute attr = new AggregatorPathAttribute(asType);
    int readableBytes = buffer.readableBytes();

    if (asType == ASType.AS_NUMBER_4OCTETS) {
        if (readableBytes != 8)
            throw new AttributeLengthException();

        attr.setAsNumber((int) buffer.readUnsignedInt());
    } else {/*from www . jav a2  s. c  om*/
        if (readableBytes != 6)
            throw new AttributeLengthException();

        attr.setAsNumber(buffer.readUnsignedShort());
    }

    try {
        byte[] addr = new byte[4];

        buffer.readBytes(addr);
        attr.setAggregator((Inet4Address) Inet4Address.getByAddress(addr));
    } catch (UnknownHostException e) {
        throw new OptionalAttributeErrorException();
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private CommunityPathAttribute decodeCommunityPathAttribute(ByteBuf buffer) {
    CommunityPathAttribute attr = new CommunityPathAttribute();

    if (buffer.readableBytes() < 4 || (buffer.readableBytes() % 4 != 0))
        throw new OptionalAttributeErrorException();

    attr.setCommunity((int) buffer.readUnsignedInt());
    while (buffer.isReadable()) {
        CommunityMember member = new CommunityMember();

        member.setAsNumber(buffer.readUnsignedShort());
        member.setMemberFlags(buffer.readUnsignedShort());

        attr.getMembers().add(member);/*from   w ww  .ja  v a 2  s.c o  m*/
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private OriginatorIDPathAttribute decodeOriginatorIDPathAttribute(ByteBuf buffer) {
    OriginatorIDPathAttribute attr = new OriginatorIDPathAttribute();

    try {//from  w  w  w  .  j a v a 2  s.  c o  m
        attr.setOriginatorID((int) buffer.readUnsignedInt());
    } catch (RuntimeException e) {
        log.error("failed to decode ORIGINATOR_ID attribute", e);

        throw new OptionalAttributeErrorException();
    }

    return attr;
}

From source file:org.bgp4j.netty.protocol.update.UpdatePacketDecoder.java

License:Apache License

private ClusterListPathAttribute decodeClusterListPathAttribute(ByteBuf buffer) {
    ClusterListPathAttribute attr = new ClusterListPathAttribute();

    try {/*from   w  w w  .  j  a va  2s  . c om*/
        while (buffer.isReadable()) {
            attr.getClusterIds().add((int) buffer.readUnsignedInt());
        }
    } catch (RuntimeException e) {
        log.error("failed to decode ORIGINATOR_ID attribute", e);

        throw new OptionalAttributeErrorException();
    }
    return attr;
}

From source file:org.eclipse.milo.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.java

License:Open Source 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  ww  .  ja  v  a  2  s  .  co 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 inner) {
                    logger.error("Error sending ErrorMessage: {}", inner.getMessage(), inner);
                }
            }
        }

        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:org.fengbaoxp.netty.official.TimeClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf time = (ByteBuf) msg;
    try {/*w w  w  .j  a  va  2  s .c  o  m*/
        long currentTimeMillis = (time.readUnsignedInt() - 2208988800L) * 1000L;
        logger.info(new Date(currentTimeMillis).toString());
        ctx.close();
    } finally {
        time.release();
    }
}

From source file:org.jfxvnc.net.rfb.codec.decoder.rect.ZlibRectDecoder.java

License:Apache License

@Override
public boolean decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!initialized) {
        if (!in.isReadable(4)) {
            return false;
        }/*from   www .j  av  a2  s. c o  m*/
        capacity = (int) in.readUnsignedInt();
        initialized = true;
    }
    return super.decode(ctx, in, out);
}