Example usage for io.netty.buffer ByteBuf readUnsignedShort

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

Introduction

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

Prototype

public abstract int readUnsignedShort();

Source Link

Document

Gets an unsigned 16-bit short integer at the current readerIndex and increases the readerIndex by 2 in this buffer.

Usage

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

License:Apache License

/**
 * decode the UPDATE network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet.
 * //from   w  w  w.ja v  a 2  s.  c o  m
 * @param buffer the buffer containing the data. 
 * @return
 */
public BGPv4Packet decodeUpdatePacket(ByteBuf buffer) {
    UpdatePacket packet = new UpdatePacket();

    ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_UPDATE, -1);

    if (buffer.readableBytes() < 2)
        throw new MalformedAttributeListException();

    // handle withdrawn routes
    int withdrawnOctets = buffer.readUnsignedShort();

    // sanity checking
    if (withdrawnOctets > buffer.readableBytes())
        throw new MalformedAttributeListException();

    ByteBuf withdrawnBuffer = null;

    if (withdrawnOctets > 0) {
        withdrawnBuffer = buffer.readSlice(withdrawnOctets);
    }

    // sanity checking
    if (buffer.readableBytes() < 2)
        throw new MalformedAttributeListException();

    // handle path attributes
    int pathAttributeOctets = buffer.readUnsignedShort();

    // sanity checking
    if (pathAttributeOctets > buffer.readableBytes())
        throw new MalformedAttributeListException();

    ByteBuf pathAttributesBuffer = null;

    if (pathAttributeOctets > 0) {
        pathAttributesBuffer = buffer.readSlice(pathAttributeOctets);
    }

    if (withdrawnBuffer != null) {
        try {
            packet.getWithdrawnRoutes().addAll(decodeWithdrawnRoutes(withdrawnBuffer));
        } catch (IndexOutOfBoundsException e) {
            throw new MalformedAttributeListException();
        }
    }

    if (pathAttributesBuffer != null) {
        try {
            packet.getPathAttributes().addAll(decodePathAttributes(pathAttributesBuffer));
        } catch (IndexOutOfBoundsException ex) {
            throw new MalformedAttributeListException();
        }
    }

    // handle network layer reachability information
    if (buffer.readableBytes() > 0) {
        try {
            while (buffer.isReadable()) {
                packet.getNlris().add(NLRICodec.decodeNLRI(buffer));
            }
        } catch (IndexOutOfBoundsException e) {
            throw new InvalidNetworkFieldException();
        } catch (IllegalArgumentException e) {
            throw new InvalidNetworkFieldException();
        }
    }

    return packet;
}

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 {/*  w w  w . ja  va  2s  .  c  o  m*/
            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 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   w  w  w  .j  a  va 2s  . 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 w  w.  j av a2  s .  co m
    }

    return attr;
}

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

License:Apache License

private MultiProtocolReachableNLRI decodeMpReachNlriPathAttribute(ByteBuf buffer) {
    MultiProtocolReachableNLRI attr = new MultiProtocolReachableNLRI();

    try {//from w  w  w  .  j  a v a  2  s .  c  om
        attr.setAddressFamily(AddressFamily.fromCode(buffer.readUnsignedShort()));
        attr.setSubsequentAddressFamily(SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()));

        int nextHopLength = buffer.readUnsignedByte();

        if (nextHopLength > 0) {
            byte[] nextHop = new byte[nextHopLength];

            buffer.readBytes(nextHop);
            attr.setNextHopAddress(nextHop);
        }

        buffer.readByte(); // reserved

        while (buffer.isReadable()) {
            attr.getNlris().add(NLRICodec.decodeNLRI(buffer));
        }
    } catch (RuntimeException e) {
        log.error("failed to decode MP_REACH_NLRI path attribute", e);

        throw new OptionalAttributeErrorException();
    }

    return attr;
}

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

License:Apache License

private MultiProtocolUnreachableNLRI decodeMpUnreachNlriPathAttribute(ByteBuf buffer) {
    MultiProtocolUnreachableNLRI attr = new MultiProtocolUnreachableNLRI();

    try {//from   w w w . ja v  a 2  s.co  m
        attr.setAddressFamily(AddressFamily.fromCode(buffer.readUnsignedShort()));
        attr.setSubsequentAddressFamily(SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()));

        while (buffer.isReadable()) {
            attr.getNlris().add(NLRICodec.decodeNLRI(buffer));
        }
    } catch (RuntimeException e) {
        log.error("failed to decode MP_UNREACH_NLRI path attribute", e);

        throw new OptionalAttributeErrorException();
    }

    return attr;
}

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

License:Apache License

private List<PathAttribute> decodePathAttributes(ByteBuf buffer) {
    List<PathAttribute> attributes = new LinkedList<PathAttribute>();

    while (buffer.isReadable()) {
        buffer.markReaderIndex();//from w  w  w. j av  a 2s  .  c  o  m

        try {
            int flagsType = buffer.readUnsignedShort();
            boolean optional = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_OPTIONAL_BIT) != 0);
            boolean transitive = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TRANSITIVE_BIT) != 0);
            boolean partial = ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_PARTIAL_BIT) != 0);
            int typeCode = (flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MASK);
            int valueLength = 0;

            if ((flagsType & BGPv4Constants.BGP_PATH_ATTRIBUTE_EXTENDED_LENGTH_BIT) != 0)
                valueLength = buffer.readUnsignedShort();
            else
                valueLength = buffer.readUnsignedByte();

            ByteBuf valueBuffer = buffer.readSlice(valueLength);

            PathAttribute attr = null;

            switch (typeCode) {
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AGGREGATOR:
                attr = decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_AGGREGATOR:
                attr = decodeAggregatorPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS4_PATH:
                attr = decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_4OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_AS_PATH:
                attr = decodeASPathAttribute(valueBuffer, ASType.AS_NUMBER_2OCTETS);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ATOMIC_AGGREGATE:
                attr = decodeAtomicAggregatePathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_COMMUNITIES:
                attr = decodeCommunityPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_LOCAL_PREF:
                attr = decodeLocalPrefPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MULTI_EXIT_DISC:
                attr = decodeMultiExitDiscPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_NEXT_HOP:
                attr = decodeNextHopPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGIN:
                attr = decodeOriginPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_REACH_NLRI:
                attr = decodeMpReachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_MP_UNREACH_NLRI:
                attr = decodeMpUnreachNlriPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_ORIGINATOR_ID:
                attr = decodeOriginatorIDPathAttribute(valueBuffer);
                break;
            case BGPv4Constants.BGP_PATH_ATTRIBUTE_TYPE_CLUSTER_LIST:
                attr = decodeClusterListPathAttribute(valueBuffer);
                break;
            default: {
                byte[] value = new byte[valueBuffer.readableBytes()];

                valueBuffer.readBytes(value);
                attr = new UnknownPathAttribute(typeCode, value);
            }
                break;
            }
            attr.setOptional(optional);
            attr.setTransitive(transitive);
            attr.setPartial(partial);

            attributes.add(attr);
        } catch (AttributeException ex) {
            int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            int attributeLength = endReadIndex - buffer.readerIndex();
            byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);
            ex.setOffendingAttribute(packet);

            throw ex;
        } catch (IndexOutOfBoundsException ex) {
            int endReadIndex = buffer.readerIndex();

            buffer.resetReaderIndex();

            int attributeLength = endReadIndex - buffer.readerIndex();
            byte[] packet = new byte[attributeLength];

            buffer.readBytes(packet);

            throw new AttributeLengthException(packet);
        }

    }

    return attributes;
}

From source file:org.dna.mqtt.moquette.parser.netty.ConnectDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException {
    in.resetReaderIndex();/*w  w w. ja  v a  2  s .  c  o m*/
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return;
    }
    int remainingLength = message.getRemainingLength();
    int start = in.readerIndex();

    int protocolNameLen = in.readUnsignedShort();
    byte[] encProtoName;
    String protoName;
    Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.PROTOCOL_VERSION);
    switch (protocolNameLen) {
    case 6:
        //MQTT version 3.1 "MQIsdp"
        //ProtocolName 8 bytes or 6 bytes
        if (in.readableBytes() < 10) {
            in.resetReaderIndex();
            return;
        }

        encProtoName = new byte[6];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQIsdp".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);

        versionAttr.set((int) VERSION_3_1);
        break;
    case 4:
        //MQTT version 3.1.1 "MQTT"
        //ProtocolName 6 bytes
        if (in.readableBytes() < 8) {
            in.resetReaderIndex();
            return;
        }
        encProtoName = new byte[4];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQTT".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);
        versionAttr.set((int) VERSION_3_1_1);
        break;
    default:
        //protocol broken
        throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen);
    }

    //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1)
    message.setProcotolVersion(in.readByte());
    if (message.getProcotolVersion() == VERSION_3_1_1) {
        //if 3.1.1, check the flags (dup, retain and qos == 0)
        if (message.isDupFlag() || message.isRetainFlag()
                || message.getQos() != AbstractMessage.QOSType.MOST_ONE) {
            throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0");
        }

        //check if this is another connect from the same client on the same session
        Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS);
        Boolean alreadyConnected = connectAttr.get();
        if (alreadyConnected == null) {
            //never set
            connectAttr.set(true);
        } else if (alreadyConnected) {
            throw new CorruptedFrameException("Received a second CONNECT on the same network connection");
        }
    }

    //Connection flag
    byte connFlags = in.readByte();
    if (message.getProcotolVersion() == VERSION_3_1_1) {
        if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0
            throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0");
        }
    }

    boolean cleanSession = ((connFlags & 0x02) >> 1) == 1;
    boolean willFlag = ((connFlags & 0x04) >> 2) == 1;
    byte willQos = (byte) ((connFlags & 0x18) >> 3);
    if (willQos > 2) {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos);
    }
    boolean willRetain = ((connFlags & 0x20) >> 5) == 1;
    boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1;
    boolean userFlag = ((connFlags & 0x80) >> 7) == 1;
    //a password is true iff user is true.
    if (!userFlag && passwordFlag) {
        in.resetReaderIndex();
        throw new CorruptedFrameException(
                "Expected password flag to true if the user flag is true but was: " + passwordFlag);
    }
    message.setCleanSession(cleanSession);
    message.setWillFlag(willFlag);
    message.setWillQos(willQos);
    message.setWillRetain(willRetain);
    message.setPasswordFlag(passwordFlag);
    message.setUserFlag(userFlag);

    //Keep Alive timer 2 bytes
    //int keepAlive = Utils.readWord(in);
    int keepAlive = in.readUnsignedShort();
    message.setKeepAlive(keepAlive);

    if ((remainingLength == 12 && message.getProcotolVersion() == VERSION_3_1)
            || (remainingLength == 10 && message.getProcotolVersion() == VERSION_3_1_1)) {
        out.add(message);
        return;
    }

    //Decode the ClientID
    String clientID = Utils.decodeString(in);
    if (clientID == null) {
        in.resetReaderIndex();
        return;
    }
    message.setClientID(clientID);

    //Decode willTopic
    if (willFlag) {
        String willTopic = Utils.decodeString(in);
        if (willTopic == null) {
            in.resetReaderIndex();
            return;
        }
        message.setWillTopic(willTopic);
    }

    //Decode willMessage
    if (willFlag) {
        String willMessage = Utils.decodeString(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return;
        }
        message.setWillMessage(willMessage);
    }

    //Compatibility check with v3.0, remaining length has precedence over
    //the user and password flags
    int readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        out.add(message);
        return;
    }

    //Decode username
    if (userFlag) {
        String userName = Utils.decodeString(in);
        if (userName == null) {
            in.resetReaderIndex();
            return;
        }
        message.setUsername(userName);
    }

    readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        out.add(message);
        return;
    }

    //Decode password
    if (passwordFlag) {
        String password = Utils.decodeString(in);
        if (password == null) {
            in.resetReaderIndex();
            return;
        }
        message.setPassword(password);
    }

    out.add(message);
}

From source file:org.dna.mqtt.moquette.parser.netty.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace("decode invoked with buffer {}", in);
    }/*  w w w.j  a v  a 2s.c  om*/
    in.resetReaderIndex();
    int startPos = in.readerIndex();

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        if (log.isDebugEnabled()) {
            log.debug("decode ask for more data after {}", in);
        }
        in.resetReaderIndex();
        return;
    }

    if (Utils.isMQTT3_1_1(ctx)) {
        if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
            //bad protocol, if QoS=0 => DUP = 0
            throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
        }

        if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
            throw new CorruptedFrameException(
                    "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
        }
    }

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return;
    }
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
    }

    message.setTopicName(topic);

    if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
            || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
        message.setMessageID(in.readUnsignedShort());
    }
    int stopPos = in.readerIndex();

    //read the payload
    int payloadSize = remainingLength - (stopPos - startPos - 2)
            + (Utils.numBytesToEncode(remainingLength) - 1);
    if (in.readableBytes() < payloadSize) {
        in.resetReaderIndex();
        return;
    }
    //        byte[] b = new byte[payloadSize];
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:org.dna.mqtt.moquette.parser.netty.SubscribeDecoder.java

License:Open Source License

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

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

    int start = in.readerIndex();
    //read  messageIDs
    message.setMessageID(in.readUnsignedShort());
    int readed = in.readerIndex() - start;
    while (readed < message.getRemainingLength()) {
        decodeSubscription(in, message);
        readed = in.readerIndex() - start;
    }

    if (message.subscriptions().isEmpty()) {
        throw new CorruptedFrameException("subscribe MUST have got at least 1 couple topic/QoS");
    }

    out.add(message);
}