Example usage for io.netty.buffer ByteBuf readSlice

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

Introduction

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

Prototype

public abstract ByteBuf readSlice(int length);

Source Link

Document

Returns a new slice of this buffer's sub-region starting at the current readerIndex and increases the readerIndex by the size of the new slice (= length ).

Usage

From source file:org.opendaylight.protocol.bgp.linkstate.spi.pojo.SimpleNlriTypeRegistry.java

License:Open Source License

private static <T> T parseTlv(final ByteBuf buffer, final LinkstateTlvParser<T> parser) {
    if (parser == null) {
        return null;
    }/*from  www. j av  a 2 s . co  m*/
    Preconditions.checkArgument(buffer != null && buffer.isReadable());
    final int length = buffer.readUnsignedShort();
    return parser.parseTlvBody(buffer.readSlice(length));
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.BGPOpenMessageParser.java

License:Open Source License

private void fillParams(final ByteBuf buffer, final List<BgpParameters> params) throws BGPDocumentedException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(), "BUffer cannot be null or empty.");
    if (LOG.isTraceEnabled()) {
        LOG.trace("Started parsing of BGP parameter: {}", ByteBufUtil.hexDump(buffer));
    }//from ww w  .  ja  v  a 2s . c o m
    while (buffer.isReadable()) {
        if (buffer.readableBytes() <= 2) {
            throw new BGPDocumentedException(
                    "Malformed parameter encountered (" + buffer.readableBytes() + " bytes left)",
                    BGPError.OPT_PARAM_NOT_SUPPORTED);
        }
        final int paramType = buffer.readUnsignedByte();
        final int paramLength = buffer.readUnsignedByte();
        final ByteBuf paramBody = buffer.readSlice(paramLength);

        final BgpParameters param;
        try {
            param = this.reg.parseParameter(paramType, paramBody);
        } catch (final BGPParsingException e) {
            throw new BGPDocumentedException("Optional parameter not parsed", BGPError.UNSPECIFIC_OPEN_ERROR,
                    e);
        }
        if (param != null) {
            params.add(param);
        } else {
            LOG.debug("Ignoring BGP Parameter type: {}", paramType);
        }
    }
    LOG.trace("Parsed BGP parameters: {}", params);
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.BGPUpdateMessageParser.java

License:Open Source License

/**
 * Parse Update message from buffer./*  w  w w  . jav a  2s .c o  m*/
 * Calls {@link #checkMandatoryAttributesPresence(Update)} to check for presence of mandatory attributes.
 *
 * @param buffer Encoded BGP message in ByteBuf
 * @param messageLength Length of the BGP message
 * @param constraint Peer specific constraints
 * @return Parsed Update message body
 * @throws BGPDocumentedException
 */
@Override
public Update parseMessageBody(final ByteBuf buffer, final int messageLength,
        final PeerSpecificParserConstraint constraint) throws BGPDocumentedException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Buffer cannot be null or empty.");

    final UpdateBuilder builder = new UpdateBuilder();

    final int withdrawnRoutesLength = buffer.readUnsignedShort();
    if (withdrawnRoutesLength > 0) {
        // TODO handle NLRI with multiple paths - requires modified yang data model
        final List<Ipv4Prefix> withdrawnRoutes = Ipv4Util
                .prefixListForBytes(ByteArray.readBytes(buffer, withdrawnRoutesLength));
        builder.setWithdrawnRoutes(new WithdrawnRoutesBuilder().setWithdrawnRoutes(withdrawnRoutes).build());
    }
    final int totalPathAttrLength = buffer.readUnsignedShort();

    if (withdrawnRoutesLength == 0 && totalPathAttrLength == 0) {
        return builder.build();
    }
    if (totalPathAttrLength > 0) {
        try {
            final Attributes attributes = this.reg.parseAttributes(buffer.readSlice(totalPathAttrLength),
                    constraint);
            builder.setAttributes(attributes);
        } catch (final RuntimeException | BGPParsingException e) {
            // Catch everything else and turn it into a BGPDocumentedException
            throw new BGPDocumentedException("Could not parse BGP attributes.", BGPError.MALFORMED_ATTR_LIST,
                    e);
        }
    }
    final List<Ipv4Prefix> nlri = Ipv4Util.prefixListForBytes(ByteArray.readAllBytes(buffer));
    if (!nlri.isEmpty()) {
        // TODO handle NLRI with multiple paths - requires modified yang data model
        builder.setNlri(new NlriBuilder().setNlri(nlri).build());
    }
    final Update msg = builder.build();
    checkMandatoryAttributesPresence(msg);
    LOG.debug("BGP Update message was parsed {}.", msg);
    return msg;
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.open.CapabilityParameterParser.java

License:Open Source License

private OptionalCapabilities parseOptionalCapability(final ByteBuf buffer)
        throws BGPDocumentedException, BGPParsingException {
    final int capCode = buffer.readUnsignedByte();
    final int capLength = buffer.readUnsignedByte();
    final ByteBuf paramBody = buffer.readSlice(capLength);
    final CParameters ret = this.reg.parseCapability(capCode, paramBody);
    if (ret == null) {
        LOG.info("Ignoring unsupported capability {}", capCode);
        return null;
    }//from  w ww  .java  2 s. c o  m
    return new OptionalCapabilitiesBuilder().setCParameters(ret).build();
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.update.AsPathAttributeParser.java

License:Open Source License

/**
 * Parses AS_PATH from bytes./*from  ww w  .j a va  2s.  c  o m*/
 *
 * @param refCache ReferenceCache shared reference of object
 * @param buffer bytes to be parsed
 * @return new ASPath object
 * @throws BGPDocumentedException if there is no AS_SEQUENCE present (mandatory)
 * @throws BGPParsingException
 */
private static AsPath parseAsPath(final ReferenceCache refCache, final ByteBuf buffer)
        throws BGPDocumentedException, BGPParsingException {
    if (!buffer.isReadable()) {
        return EMPTY;
    }
    final ArrayList<Segments> ases = new ArrayList<>();
    boolean isSequence = false;
    while (buffer.isReadable()) {
        final int type = buffer.readUnsignedByte();
        final SegmentType segmentType = AsPathSegmentParser.parseType(type);
        if (segmentType == null) {
            throw new BGPParsingException("AS Path segment type unknown : " + type);
        }
        final int count = buffer.readUnsignedByte();

        final List<AsNumber> asList = AsPathSegmentParser.parseAsSegment(refCache, count,
                buffer.readSlice(count * AsPathSegmentParser.AS_NUMBER_LENGTH));
        if (segmentType == SegmentType.AS_SEQUENCE) {
            ases.add(new SegmentsBuilder().setAsSequence(asList).build());
            isSequence = true;
        } else {
            ases.add(new SegmentsBuilder().setAsSet(asList).build());
        }
    }
    if (!isSequence) {
        throw new BGPDocumentedException("AS_SEQUENCE must be present in AS_PATH attribute.",
                BGPError.AS_PATH_MALFORMED);
    }

    ases.trimToSize();
    return new AsPathBuilder().setSegments(ases).build();
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.update.CommunitiesAttributeParser.java

License:Open Source License

@Override
public void parseAttribute(final ByteBuf buffer, final AttributesBuilder builder)
        throws BGPDocumentedException {
    final List<Communities> set = Lists.newArrayList();
    while (buffer.isReadable()) {
        set.add((Communities) parseCommunity(this.refCache, buffer.readSlice(COMMUNITY_LENGTH)));
    }/*from  w  w w.  ja  v a  2  s .c  o m*/
    builder.setCommunities(set);
}

From source file:org.opendaylight.protocol.bgp.parser.spi.AbstractMessageRegistry.java

License:Open Source License

@Override
public Notification parseMessage(final ByteBuf buffer, final PeerSpecificParserConstraint constraint)
        throws BGPDocumentedException, BGPParsingException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(),
            "Array of bytes cannot be null or empty.");
    Preconditions.checkArgument(buffer.readableBytes() >= MessageUtil.COMMON_HEADER_LENGTH,
            "Too few bytes in passed array. Passed: %s. Expected: >= %s.", buffer.readableBytes(),
            MessageUtil.COMMON_HEADER_LENGTH);
    final byte[] marker = ByteArray.readBytes(buffer, MessageUtil.MARKER_LENGTH);

    if (!Arrays.equals(marker, MARKER)) {
        throw new BGPDocumentedException("Marker not set to ones.", BGPError.CONNECTION_NOT_SYNC);
    }//from www  . j  a  v  a  2 s .c om
    final int messageLength = buffer.readUnsignedShort();
    // to be sent with Error message
    final byte typeBytes = buffer.readByte();
    final int messageType = UnsignedBytes.toInt(typeBytes);

    if (messageLength < MessageUtil.COMMON_HEADER_LENGTH) {
        throw BGPDocumentedException.badMessageLength("Message length field not within valid range.",
                messageLength);
    }

    if (messageLength - MessageUtil.COMMON_HEADER_LENGTH != buffer.readableBytes()) {
        throw new BGPParsingException(
                "Size doesn't match size specified in header. Passed: " + buffer.readableBytes()
                        + "; Expected: " + (messageLength - MessageUtil.COMMON_HEADER_LENGTH) + ". ");
    }

    final ByteBuf msgBody = buffer.readSlice(messageLength - MessageUtil.COMMON_HEADER_LENGTH);

    final Notification msg = parseBody(messageType, msgBody, messageLength, constraint);
    if (msg == null) {
        throw new BGPDocumentedException("Unhandled message type " + messageType, BGPError.BAD_MSG_TYPE,
                new byte[] { typeBytes });
    }
    return msg;
}

From source file:org.opendaylight.protocol.bgp.parser.spi.pojo.SimpleAttributeRegistry.java

License:Open Source License

private void addAttribute(final ByteBuf buffer, final Map<Integer, RawAttribute> attributes)
        throws BGPDocumentedException {
    final BitArray flags = BitArray.valueOf(buffer.readByte());
    final int type = buffer.readUnsignedByte();
    final int len = (flags.get(EXTENDED_LENGTH_BIT)) ? buffer.readUnsignedShort() : buffer.readUnsignedByte();
    if (!attributes.containsKey(type)) {
        final AttributeParser parser = this.handlers.getParser(type);
        if (parser == null) {
            processUnrecognized(flags, type, buffer, len);
        } else {//from  w  w w  .  j a  v a  2 s . c  o  m
            attributes.put(type, new RawAttribute(parser, buffer.readSlice(len)));
        }
    } else {
        LOG.debug("Ignoring duplicate attribute type {}", type);
    }
}

From source file:org.opendaylight.protocol.bgp.parser.spi.pojo.SimpleNlriRegistry.java

License:Open Source License

@Override
public MpReachNlri parseMpReach(final ByteBuf buffer, final PeerSpecificParserConstraint constraint)
        throws BGPParsingException {
    final MpReachNlriBuilder builder = new MpReachNlriBuilder();
    final Class<? extends AddressFamily> afi = getAfi(buffer);
    final Class<? extends SubsequentAddressFamily> safi = getSafi(buffer);
    builder.setAfi(afi);//from ww w . ja va 2s  .  c o  m
    builder.setSafi(safi);

    final BgpTableType key = createKey(builder.getAfi(), builder.getSafi());

    final int nextHopLength = buffer.readUnsignedByte();
    if (nextHopLength != 0) {
        final NextHopParserSerializer nextHopParser = this.nextHopParsers.get(key);
        if (nextHopParser != null) {
            builder.setCNextHop(nextHopParser.parseNextHop(buffer.readSlice(nextHopLength)));
        } else {
            builder.setCNextHop(NextHopUtil.parseNextHop(buffer.readSlice(nextHopLength)));
            LOG.warn("NexHop Parser/Serializer for AFI/SAFI ({},{}) not bound", afi, safi);
        }
    }
    buffer.skipBytes(RESERVED);

    final ByteBuf nlri = buffer.slice();
    final NlriParser parser = this.handlers.get(key);
    if (parser == null) {
        LOG.warn(PARSER_NOT_FOUND, key);
    } else {
        parser.parseNlri(nlri, builder, constraint);
    }
    return builder.build();
}

From source file:org.opendaylight.protocol.bmp.impl.message.PeerUpHandler.java

License:Open Source License

@Override
public Notification parseMessageBody(final ByteBuf bytes) throws BmpDeserializationException {
    final PeerUpNotificationBuilder peerUpNot = new PeerUpNotificationBuilder()
            .setPeerHeader(parsePerPeerHeader(bytes));

    if (peerUpNot.getPeerHeader().isIpv4()) {
        bytes.skipBytes(Ipv6Util.IPV6_LENGTH - Ipv4Util.IP4_LENGTH);
        peerUpNot.setLocalAddress(new IpAddress(Ipv4Util.addressForByteBuf(bytes)));
    } else {/*  w w  w . j a va  2  s  . c o  m*/
        peerUpNot.setLocalAddress(new IpAddress(Ipv6Util.addressForByteBuf(bytes)));
    }
    peerUpNot.setLocalPort(new PortNumber(bytes.readUnsignedShort()));
    peerUpNot.setRemotePort(new PortNumber(bytes.readUnsignedShort()));
    try {
        final Notification opSent = getBgpMessageRegistry()
                .parseMessage(bytes.readSlice(getBgpMessageLength(bytes)));
        Preconditions.checkNotNull(opSent, "Error on parse Sent OPEN Message, Sent OPEN Message is null");
        Preconditions.checkArgument(opSent instanceof OpenMessage,
                "An instance of OpenMessage notification is required");
        final OpenMessage sent = (OpenMessage) opSent;

        final Notification opRec = getBgpMessageRegistry()
                .parseMessage(bytes.readSlice(getBgpMessageLength(bytes)));
        Preconditions.checkNotNull(opRec,
                "Error on parse Received  OPEN Message, Received  OPEN Message is null");
        Preconditions.checkArgument(opRec instanceof OpenMessage,
                "An instance of OpenMessage notification is required");
        final OpenMessage received = (OpenMessage) opRec;

        peerUpNot.setSentOpen(new SentOpenBuilder(sent).build());
        peerUpNot.setReceivedOpen(new ReceivedOpenBuilder(received).build());

        final InformationBuilder infos = new InformationBuilder();
        if (bytes.isReadable()) {
            parseTlvs(infos, bytes);
            peerUpNot.setInformation(infos.build());
        }

    } catch (final BGPDocumentedException | BGPParsingException e) {
        throw new BmpDeserializationException("Error while parsing BGP Open Message.", e);
    }

    return peerUpNot.build();
}