Java Code Examples for org.jboss.netty.buffer.ChannelBuffer#skipBytes()

The following examples show how to use org.jboss.netty.buffer.ChannelBuffer#skipBytes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RPCRecordDecoder.java    From nfs-client-java with Apache License 2.0 5 votes vote down vote up
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {
    // Wait until the length prefix is available.
    if (channelBuffer.readableBytes() < 4) {
        // If null is returned, it means there is not enough data yet.
        // FrameDecoder will call again when there is a sufficient amount of data available.
        return null;
    }

    //marking the current reading position
    channelBuffer.markReaderIndex();

    //get the fragment size and wait until the entire fragment is available.
    long fragSize = channelBuffer.readUnsignedInt();
    boolean lastFragment = RecordMarkingUtil.isLastFragment(fragSize);
    fragSize = RecordMarkingUtil.maskFragmentSize(fragSize);
    if (channelBuffer.readableBytes() < fragSize) {
        channelBuffer.resetReaderIndex();
        return null;
    }

    //seek to the beginning of the next fragment
    channelBuffer.skipBytes((int) fragSize);

    _recordLength += 4 + (int) fragSize;

    //check the last fragment
    if (!lastFragment) {
        //not the last fragment, the data is put in an internally maintained cumulative buffer
        return null;
    }

    byte[] rpcResponse = new byte[_recordLength];
    channelBuffer.readerIndex(channelBuffer.readerIndex() - _recordLength);
    channelBuffer.readBytes(rpcResponse, 0, _recordLength);

    _recordLength = 0;
    return rpcResponse;
}
 
Example 2
Source File: MessagePackStreamDecoder.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer source) throws Exception {
    // TODO #MN will modify the body with MessagePackBufferUnpacker.
    ByteBuffer buffer = source.toByteBuffer();
    if (!buffer.hasRemaining()) {
        return null;
    }
    source.markReaderIndex();

    byte[] bytes = buffer.array(); // FIXME buffer must has array
    int offset = buffer.arrayOffset() + buffer.position();
    int length = buffer.arrayOffset() + buffer.limit();
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes, offset,
            length);
    int startAvailable = stream.available();
    try{
        Unpacker unpacker = msgpack.createUnpacker(stream);
        Value v = unpacker.readValue();
        source.skipBytes(startAvailable - stream.available());
        return v;
    }catch( EOFException e ){
        // not enough buffers.
        // So retry reading
        source.resetReaderIndex();
        return null;
    }
}
 
Example 3
Source File: PcepIroObjectVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns linked list of sub objects.
 *
 * @param cb of type channel buffer
 * @return linked list of sub objects
 * @throws PcepParseException while parsing subobjects from channel buffer
 */
protected static LinkedList<PcepValueType> parseSubObjects(ChannelBuffer cb) throws PcepParseException {

    LinkedList<PcepValueType> llSubObjects = new LinkedList<>();

    while (0 < cb.readableBytes()) {

        //check the Type of the Subobjects.
        byte yType = cb.readByte();
        yType = (byte) (yType & (YTYPE_SHIFT_VALUE));
        byte hLength = cb.readByte();

        PcepValueType subObj;
        switch (yType) {

        case IPv4SubObject.TYPE:
            subObj = IPv4SubObject.read(cb);
            break;

        default:
            throw new PcepParseException("Invalid sub object. Type: " + (int) yType);
        }

        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }
        llSubObjects.add(subObj);
    }
    return llSubObjects;
}
 
Example 4
Source File: PcepLabelRangeObjectVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns list of optional tlvs.
 *
 * @param cb of type channle buffer
 * @return list of optional tlvs
 * @throws PcepParseException whne fails to parse list of optional tlvs
 */
public static LinkedList<PcepValueType> parseOptionalTlv(ChannelBuffer cb) throws PcepParseException {

    LinkedList<PcepValueType> llOutOptionalTlv = new LinkedList<>();

    while (MINIMUM_COMMON_HEADER_LENGTH <= cb.readableBytes()) {

        PcepValueType tlv;
        int iValue;
        short hType = cb.readShort();
        short hLength = cb.readShort();

        switch (hType) {

        case PathSetupTypeTlv.TYPE:
            iValue = cb.readInt();
            tlv = new PathSetupTypeTlv(iValue);
            break;

        default:
            throw new PcepParseException("Unsupported TLV in LabelRange Object.");
        }

        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }
        llOutOptionalTlv.add(tlv);
    }
    return llOutOptionalTlv;
}
 
Example 5
Source File: IsisMessageDecoder.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the source MAC address from the ethernet header.
 *
 * @param ethHeader ethernet header bytes
 * @return MAC address of the source router
 */
private MacAddress getSourceMac(ChannelBuffer ethHeader) {
    //Source MAC is at position 6 to 11 (6 bytes)
    ethHeader.skipBytes(IsisUtil.SIX_BYTES);
    MacAddress sourceMac = MacAddress.valueOf(ethHeader.readBytes(IsisUtil.SIX_BYTES).array());

    return sourceMac;
}
 
Example 6
Source File: Message.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public String readCString( ChannelBuffer buffer ) {
    int i = buffer.bytesBefore( ( byte ) 0 );
    if ( i < 0 ) {
        return null;
    }
    String s = buffer.toString( buffer.readerIndex(), i, Charset.forName( "UTF-8" ) );
    buffer.skipBytes( i + 1 );
    return s;
}
 
Example 7
Source File: NodeAttributesTlv.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Reads the channel buffer and returns object of NodeAttributesTlv.
 *
 * @param c input channel buffer
 * @param hLength length
 * @return object of NodeAttributesTlv
 * @throws PcepParseException if mandatory fields are missing
 */
public static PcepValueType read(ChannelBuffer c, short hLength) throws PcepParseException {

    // Node Descriptor Sub-TLVs (variable)
    List<PcepValueType> llNodeAttributesSubTLVs = new LinkedList<>();

    ChannelBuffer tempCb = c.readBytes(hLength);

    while (TLV_HEADER_LENGTH <= tempCb.readableBytes()) {
        PcepValueType tlv;
        short hType = tempCb.readShort();
        int iValue = 0;
        short length = tempCb.readShort();
        switch (hType) {

        case NodeFlagBitsSubTlv.TYPE:
            byte cValue = tempCb.readByte();
            tlv = new NodeFlagBitsSubTlv(cValue);
            break;
        case OpaqueNodePropertiesSubTlv.TYPE:
            tlv = OpaqueNodePropertiesSubTlv.read(tempCb, length);
            break;
        case NodeNameSubTlv.TYPE:
            tlv = NodeNameSubTlv.read(tempCb, length);
            break;
        case IsisAreaIdentifierSubTlv.TYPE:
            tlv = IsisAreaIdentifierSubTlv.read(tempCb, length);
            break;
        case IPv4RouterIdOfLocalNodeSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new IPv4RouterIdOfLocalNodeSubTlv(iValue);
            break;
        case IPv6RouterIdofLocalNodeSubTlv.TYPE:
            byte[] ipv6Value = new byte[IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH];
            tempCb.readBytes(ipv6Value, 0, IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH);
            tlv = new IPv6RouterIdofLocalNodeSubTlv(ipv6Value);
            break;
        default:
            throw new PcepParseException("Unsupported Sub TLV type :" + hType);
        }

        // Check for the padding
        int pad = length % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= tempCb.readableBytes()) {
                tempCb.skipBytes(pad);
            }
        }

        llNodeAttributesSubTLVs.add(tlv);
    }

    if (0 < tempCb.readableBytes()) {

        throw new PcepParseException("Sub Tlv parsing error. Extra bytes received.");
    }
    return new NodeAttributesTlv(llNodeAttributesSubTLVs);
}
 
Example 8
Source File: PcepStateReportVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Reads all the Objects for PCEP Message Path.
 *
 * @param bb of type channel buffer
 * @return PCEP Message path
 * @throws PcepParseException when fails to read pcep message path
 */
@Override
public PcepMsgPath read(ChannelBuffer bb) throws PcepParseException {

    PcepEroObject eroObj;
    PcepAttribute attrList;
    PcepRroObject rroObj = null;
    PcepBandwidthObject bandwidth = null;

    eroObj = PcepEroObjectVer1.read(bb);
    attrList = PcepAttributeVer1.read(bb);

    boolean bBreakWhile = false;
    while (0 < bb.readableBytes()) {

        if (bb.readableBytes() < OBJECT_HEADER_LENGTH) {
            break;
        }
        bb.markReaderIndex();
        PcepObjectHeader tempObjHeader = PcepObjectHeader.read(bb);
        bb.resetReaderIndex();
        byte yObjClass = tempObjHeader.getObjClass();

        switch (yObjClass) {
        case PcepRroObjectVer1.RRO_OBJ_CLASS:
            rroObj = PcepRroObjectVer1.read(bb);
            break;
        case PcepInterLayerObjectVer1.INTER_LAYER_OBJ_CLASS:
            bb.skipBytes(tempObjHeader.getObjLen());
            break;
        case PcepBandwidthObjectVer1.BANDWIDTH_OBJ_CLASS:
            bandwidth = PcepBandwidthObjectVer1.read(bb);
            break;
        default:
            //Otherthan above objects handle those objects in caller.
            bBreakWhile = true;
            break;
        }
        if (bBreakWhile) {
            break;
        }
    }
    return new PcepMsgPath(eroObj, attrList, rroObj, bandwidth);
}
 
Example 9
Source File: PcepLabelObjectVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns list of optional tlvs.
 *
 * @param cb of type channel buffer
 * @return list of optional tlvs.
 * @throws PcepParseException when fails to parse list of optional tlvs
 */
protected static LinkedList<PcepValueType> parseOptionalTlv(ChannelBuffer cb) throws PcepParseException {

    LinkedList<PcepValueType> llOutOptionalTlv = new LinkedList<>();

    while (MINIMUM_COMMON_HEADER_LENGTH <= cb.readableBytes()) {

        PcepValueType tlv;
        short hType = cb.readShort();
        short hLength = cb.readShort();
        int iValue = 0;

        switch (hType) {

        case NexthopIPv4addressTlv.TYPE:
            iValue = cb.readInt();
            tlv = new NexthopIPv4addressTlv(iValue);
            break;
        case NexthopIPv6addressTlv.TYPE:
            byte[] ipv6Value = new byte[NexthopIPv6addressTlv.VALUE_LENGTH];
            cb.readBytes(ipv6Value, 0, NexthopIPv6addressTlv.VALUE_LENGTH);
            tlv = new NexthopIPv6addressTlv(ipv6Value);
            break;
        case NexthopUnnumberedIPv4IDTlv.TYPE:
            tlv = NexthopUnnumberedIPv4IDTlv.read(cb);
            break;
        default:
            throw new PcepParseException("Unsupported TLV type :" + hType);
        }

        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }

        llOutOptionalTlv.add(tlv);
    }

    if (0 < cb.readableBytes()) {

        throw new PcepParseException("Optional Tlv parsing error. Extra bytes received.");
    }
    return llOutOptionalTlv;
}
 
Example 10
Source File: PcepLspObjectVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns Linked list of optional tlvs.
 *
 * @param cb of channel buffer.
 * @return list of optional tlvs
 * @throws PcepParseException when unsupported tlv is received
 */
protected static LinkedList<PcepValueType> parseOptionalTlv(ChannelBuffer cb) throws PcepParseException {

    LinkedList<PcepValueType> llOutOptionalTlv;

    llOutOptionalTlv = new LinkedList<>();

    while (MINIMUM_COMMON_HEADER_LENGTH <= cb.readableBytes()) {

        PcepValueType tlv = null;
        short hType = cb.readShort();
        short hLength = cb.readShort();
        int iValue = 0;

        switch (hType) {

        case StatefulIPv4LspIdentifiersTlv.TYPE:
            tlv = StatefulIPv4LspIdentifiersTlv.read(cb);
            break;
        case StatefulLspErrorCodeTlv.TYPE:
            iValue = cb.readInt();
            tlv = new StatefulLspErrorCodeTlv(iValue);
            break;
        case StatefulRsvpErrorSpecTlv.TYPE:
            tlv = StatefulRsvpErrorSpecTlv.read(cb);
            break;
        case SymbolicPathNameTlv.TYPE:
            tlv = SymbolicPathNameTlv.read(cb, hLength);
            break;
        case StatefulLspDbVerTlv.TYPE:
            tlv = StatefulLspDbVerTlv.read(cb);
            break;
        default:
            // Skip the unknown TLV.
            cb.skipBytes(hLength);
            log.info("Received unsupported TLV type :" + hType + " in LSP object.");
        }
        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }

        if (tlv != null) {
            llOutOptionalTlv.add(tlv);
        }
    }

    if (0 < cb.readableBytes()) {

        throw new PcepParseException("Optional Tlv parsing error. Extra bytes received.");
    }
    return llOutOptionalTlv;
}
 
Example 11
Source File: PcepSrpObjectVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Parse Optional TLvs from the channel buffer.
 *
 * @param cb of type channel buffer
 * @return list of optional tlvs
 * @throws PcepParseException when unsupported tlv is received in srp object
 */
public static LinkedList<PcepValueType> parseOptionalTlv(ChannelBuffer cb) throws PcepParseException {

    LinkedList<PcepValueType> llOutOptionalTlv = new LinkedList<>();

    while (MINIMUM_COMMON_HEADER_LENGTH <= cb.readableBytes()) {

        PcepValueType tlv;
        short hType = cb.readShort();
        short hLength = cb.readShort();

        switch (hType) {
        case SymbolicPathNameTlv.TYPE:
            if (cb.readableBytes() < hLength) {
                throw new PcepParseException("Length is not valid in SymbolicPathNameTlv");
            }
            tlv = SymbolicPathNameTlv.read(cb, hLength);
            break;
        case PathSetupTypeTlv.TYPE:
            if (cb.readableBytes() != PathSetupTypeTlv.LENGTH) {
                throw new PcepParseException("Length is not valid in PathSetupTypeTlv");
            }
            tlv = PathSetupTypeTlv.of(cb.readInt());
            break;
        default:
            // Skip the unknown TLV.
            cb.skipBytes(hLength);
            tlv = null;
            log.info("Received unsupported TLV type :" + hType + " in SRP object.");
        }

        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }

        if (tlv != null) {
            llOutOptionalTlv.add(tlv);
        }
    }

    return llOutOptionalTlv;
}
 
Example 12
Source File: MemcachedCommandDecoder.java    From fqueue with Apache License 2.0 4 votes vote down vote up
/**
 * Process an inbound string from the pipeline's downstream, and depending
 * on the state (waiting for data or processing commands), turn them into
 * the correct type of command.
 * 
 * @param channelHandlerContext
 * @param messageEvent
 * @throws Exception
 */
@Override
public void messageReceived(ChannelHandlerContext channelHandlerContext, MessageEvent messageEvent)
		throws Exception {
	ChannelBuffer in = (ChannelBuffer) messageEvent.getMessage();

	try {
		// Because of the frame handler, we are assured that we are
		// receiving only complete lines or payloads.
		// Verify that we are in 'processing()' mode
		if (status.state == SessionStatus.State.PROCESSING) {
			// split into pieces
			List<String> pieces = new ArrayList<String>(6);
			int pos = in.bytesBefore(space);
			do {
				if (pos != -1) {
					pieces.add(in.toString(in.readerIndex(), pos, USASCII));
					in.skipBytes(pos + 1);
				}
			} while ((pos = in.bytesBefore(space)) != -1);
			pieces.add(in.toString(USASCII));

			processLine(pieces, messageEvent.getChannel(), channelHandlerContext);
		} else if (status.state == SessionStatus.State.PROCESSING_MULTILINE) {
			ChannelBuffer slice = in.copy();
			byte[] payload = slice.array();
			in.skipBytes(in.readableBytes());
			continueSet(messageEvent.getChannel(), status, payload, channelHandlerContext);
		} else {
			throw new InvalidProtocolStateException("invalid protocol state");
		}

	} finally {
		// Now indicate that we need more for this command by changing the
		// session status's state.
		// This instructs the frame decoder to start collecting data for us.
		// Note, we don't do this if we're waiting for data.
		if (status.state != SessionStatus.State.WAITING_FOR_DATA)
			status.ready();
	}
}
 
Example 13
Source File: MemcachedFrameDecoder.java    From fqueue with Apache License 2.0 4 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, org.jboss.netty.channel.Channel channel, ChannelBuffer buffer)
		throws Exception {
	// check the state. if we're WAITING_FOR_DATA that means instead of
	// breaking into lines, we need N bytes
	// otherwise, we're waiting for input
	if (status.state == SessionStatus.State.WAITING_FOR_DATA) {
		if (buffer.readableBytes() < status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity())
			return null;

		// verify delimiter matches at the right location
		ChannelBuffer dest = buffer.slice(status.bytesNeeded + buffer.readerIndex(), 2);
		StatsCounter.bytes_written.addAndGet(status.bytesNeeded);
		if (!dest.equals(MemcachedResponseEncoder.CRLF)) {
			// before we throw error... we're ready for the next command
			status.ready();

			// error, no delimiter at end of payload
			throw new IncorrectlyTerminatedPayloadException("payload not terminated correctly");
		} else {
			status.processingMultiline();

			// There's enough bytes in the buffer and the delimiter is at
			// the end. Read it.
			ChannelBuffer result = buffer.slice(buffer.readerIndex(), status.bytesNeeded);
			buffer.skipBytes(status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity());

			return result;
		}

	} else {
		int minFrameLength = Integer.MAX_VALUE;
		ChannelBuffer foundDelimiter = null;
		// command length
		int frameLength = buffer.bytesBefore(buffer.readerIndex(), buffer.readableBytes(),
				ChannelBufferIndexFinder.CRLF);
		if (frameLength >= 0 && frameLength < minFrameLength && buffer.readableBytes() >= frameLength + 2) {
			minFrameLength = frameLength;
			foundDelimiter = MemcachedResponseEncoder.CRLF;
		}

		if (foundDelimiter != null) {
			int minDelimLength = foundDelimiter.capacity();

			if (discardingTooLongFrame) {
				// We've just finished discarding a very large frame.
				// Throw an exception and go back to the initial state.
				long tooLongFrameLength = this.tooLongFrameLength;
				this.tooLongFrameLength = 0L;
				discardingTooLongFrame = false;
				buffer.skipBytes(minFrameLength + minDelimLength);
				fail(tooLongFrameLength + minFrameLength + minDelimLength);
			}

			if (minFrameLength > maxFrameLength) {
				// Discard read frame.
				buffer.skipBytes(minFrameLength + minDelimLength);
				StatsCounter.bytes_written.addAndGet(minFrameLength + minDelimLength);
				fail(minFrameLength);
			}

			ChannelBuffer frame = buffer.slice(buffer.readerIndex(), minFrameLength);
			buffer.skipBytes(minFrameLength + minDelimLength);
			status.processing();
			StatsCounter.bytes_written.addAndGet(minFrameLength + minDelimLength);
			return frame;
		} else {
			if (buffer.readableBytes() > maxFrameLength) {
				// Discard the content of the buffer until a delimiter is
				// found.
				tooLongFrameLength = buffer.readableBytes();
				buffer.skipBytes(buffer.readableBytes());
				discardingTooLongFrame = true;
				StatsCounter.bytes_written.addAndGet(tooLongFrameLength);
			}

			return null;
		}
	}
}
 
Example 14
Source File: PcepLSObjectVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns Linked list of PCEP Value Type.
 *
 * @param cb of channel buffer
 * @return Linked list of PCEP Value Type
 * @throws PcepParseException if mandatory fields are missing
 */
protected static List<PcepValueType> parseOptionalTlv(ChannelBuffer cb) throws PcepParseException {

    List<PcepValueType> llOutOptionalTlv;

    llOutOptionalTlv = new LinkedList<>();

    while (MINIMUM_TLV_HEADER_LENGTH <= cb.readableBytes()) {

        PcepValueType tlv;
        short hType = cb.readShort();
        short hLength = cb.readShort();
        long lValue = 0;

        switch (hType) {

        case RoutingUniverseTlv.TYPE:
            lValue = cb.readLong();
            tlv = new RoutingUniverseTlv(lValue);
            break;
        case LocalNodeDescriptorsTlv.TYPE:
            tlv = LocalNodeDescriptorsTlv.read(cb, hLength);
            break;
        case RemoteNodeDescriptorsTlv.TYPE:
            tlv = RemoteNodeDescriptorsTlv.read(cb, hLength);
            break;
        case LinkDescriptorsTlv.TYPE:
            tlv = LinkDescriptorsTlv.read(cb, hLength);
            break;
        case NodeAttributesTlv.TYPE:
            tlv = NodeAttributesTlv.read(cb, hLength);
            break;
        case LinkAttributesTlv.TYPE:
            tlv = LinkAttributesTlv.read(cb, hLength);
            break;
        default:
            throw new PcepParseException("Unsupported TLV type :" + hType);
        }

        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }

        llOutOptionalTlv.add(tlv);
    }

    if (0 < cb.readableBytes()) {

        throw new PcepParseException("Optional Tlv parsing error. Extra bytes received.");
    }
    return llOutOptionalTlv;
}
 
Example 15
Source File: PcepLspaObjectVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Writes optional tlvs to channel buffer.
 *
 * @param cb channel buffer
 * @return true
 */
protected boolean packOptionalTlv(ChannelBuffer cb) {
    int hTlvType;
    int hTlvLength;

    ListIterator<PcepValueType> listIterator = llOptionalTlv.listIterator();
    while (listIterator.hasNext()) {
        PcepValueType tlv = listIterator.next();
        if (tlv == null) {
            log.debug("Warning: tlv is null from OptionalTlv list");
            continue;
        }
        hTlvType = tlv.getType();
        hTlvLength = tlv.getLength();
        if (0 == hTlvLength) {
            log.debug("Warning: invalid length in tlv of OptionalTlv list");
            continue;
        }

        cb.writeShort(hTlvType);
        cb.writeShort(hTlvLength);

        switch (hTlvType) {
        //TODO: optional TLV for LSPA to be added

        default:
            log.debug("Warning: PcepLspaObject: unknown tlv");
        }

        // As per RFC the length of object should
        // be multiples of 4
        int pad = hTlvLength % 4;

        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }
    }
    return true;
}
 
Example 16
Source File: PcepEroObjectVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Parse list of Sub Objects.
 *
 * @param cb channel buffer
 * @return list of Sub Objects
 * @throws PcepParseException when fails to parse sub object list
 */
protected static LinkedList<PcepValueType> parseSubObjects(ChannelBuffer cb) throws PcepParseException {

    LinkedList<PcepValueType> subObjectList = new LinkedList<>();

    while (0 < cb.readableBytes()) {

        //check the Type of the TLV
        short type = cb.readByte();
        type = (short) (type & (TYPE_SHIFT_VALUE));
        byte hLength = cb.readByte();

        PcepValueType subObj;

        switch (type) {

        case IPv4SubObject.TYPE:
            subObj = IPv4SubObject.read(cb);
            break;
        case IPv6SubObject.TYPE:
            byte[] ipv6Value = new byte[IPv6SubObject.VALUE_LENGTH];
            cb.readBytes(ipv6Value, 0, IPv6SubObject.VALUE_LENGTH);
            subObj = new IPv6SubObject(ipv6Value);
            break;
        case AutonomousSystemNumberSubObject.TYPE:
            subObj = AutonomousSystemNumberSubObject.read(cb);
            break;
        case PathKeySubObject.TYPE:
            subObj = PathKeySubObject.read(cb);
            break;
        case SrEroSubObject.TYPE:
            subObj = SrEroSubObject.read(cb);
            break;
        default:
            throw new PcepParseException("Unexpected sub object. Type: " + (int) type);
        }
        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= cb.readableBytes()) {
                cb.skipBytes(pad);
            }
        }

        subObjectList.add(subObj);
    }
    if (0 < cb.readableBytes()) {
        throw new PcepParseException("Subobject parsing error. Extra bytes received.");
    }
    return subObjectList;
}
 
Example 17
Source File: RemoteNodeDescriptorsTlv.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Reads channel buffer and returns object of Remote TE Node Descriptors TLV.
 *
 * @param c input channel buffer
 * @param length length of buffer
 * @return object of RemoteNodeDescriptorsTlv
 * @throws PcepParseException if mandatory fields are missing
 */
public static PcepValueType read(ChannelBuffer c, short length) throws PcepParseException {

    // Node Descriptor Sub-TLVs (variable)
    List<PcepValueType> llRemoteTENodeDescriptorSubTLVs = new LinkedList<>();

    ChannelBuffer tempCb = c.readBytes(length);

    while (TLV_HEADER_LENGTH <= tempCb.readableBytes()) {

        PcepValueType tlv;
        short hType = tempCb.readShort();
        int iValue = 0;
        short hLength = tempCb.readShort();
        switch (hType) {

        case AutonomousSystemSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new AutonomousSystemSubTlv(iValue);
            break;
        case BgpLsIdentifierSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new BgpLsIdentifierSubTlv(iValue);
            break;
        case OspfAreaIdSubTlv.TYPE:
            iValue = tempCb.readInt();
            tlv = new OspfAreaIdSubTlv(iValue);
            break;
        case IgpRouterIdSubTlv.TYPE:
            tlv = IgpRouterIdSubTlv.read(tempCb, hLength);
            break;

        default:
            throw new PcepParseException("Unsupported Sub TLV type :" + hType);
        }

        // Check for the padding
        int pad = hLength % 4;
        if (0 < pad) {
            pad = 4 - pad;
            if (pad <= tempCb.readableBytes()) {
                tempCb.skipBytes(pad);
            }
        }

        llRemoteTENodeDescriptorSubTLVs.add(tlv);
    }

    if (0 < tempCb.readableBytes()) {

        throw new PcepParseException("Sub Tlv parsing error. Extra bytes received.");
    }
    return new RemoteNodeDescriptorsTlv(llRemoteTENodeDescriptorSubTLVs);
}
 
Example 18
Source File: SizeHeaderFrameDecoder.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
    if (buffer.readableBytes() < 6) {
        return null;
    }

    int readerIndex = buffer.readerIndex();
    if (buffer.getByte(readerIndex) != 'E' || buffer.getByte(readerIndex + 1) != 'S') {
        // special handling for what is probably HTTP
        if (bufferStartsWith(buffer, readerIndex, "GET ") ||
            bufferStartsWith(buffer, readerIndex, "POST ") ||
            bufferStartsWith(buffer, readerIndex, "PUT ") ||
            bufferStartsWith(buffer, readerIndex, "HEAD ") ||
            bufferStartsWith(buffer, readerIndex, "DELETE ") ||
            bufferStartsWith(buffer, readerIndex, "OPTIONS ") ||
            bufferStartsWith(buffer, readerIndex, "PATCH ") ||
            bufferStartsWith(buffer, readerIndex, "TRACE ")) {

            throw new HttpOnTransportException("This is not a HTTP port");
        }

        // we have 6 readable bytes, show 4 (should be enough)
        throw new StreamCorruptedException("invalid internal transport message format, got ("
                + Integer.toHexString(buffer.getByte(readerIndex) & 0xFF) + ","
                + Integer.toHexString(buffer.getByte(readerIndex + 1) & 0xFF) + ","
                + Integer.toHexString(buffer.getByte(readerIndex + 2) & 0xFF) + ","
                + Integer.toHexString(buffer.getByte(readerIndex + 3) & 0xFF) + ")");
    }

    int dataLen = buffer.getInt(buffer.readerIndex() + 2);
    if (dataLen == NettyHeader.PING_DATA_SIZE) {
        // discard the messages we read and continue, this is achieved by skipping the bytes
        // and returning null
        buffer.skipBytes(6);
        return null;
    }
    if (dataLen <= 0) {
        throw new StreamCorruptedException("invalid data length: " + dataLen);
    }
    // safety against too large frames being sent
    if (dataLen > NINETY_PER_HEAP_SIZE) {
        throw new TooLongFrameException(
                "transport content length received [" + new ByteSizeValue(dataLen) + "] exceeded [" + new ByteSizeValue(NINETY_PER_HEAP_SIZE) + "]");
    }

    if (buffer.readableBytes() < dataLen + 6) {
        return null;
    }
    buffer.skipBytes(6);
    return buffer;
}
 
Example 19
Source File: UnSupportedAttribute.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Reads channel buffer parses attribute header and skips specified length.
 *
 * @param cb channelBuffer
 */
public static void read(ChannelBuffer cb) {
    Validation parseFlags = Validation.parseAttributeHeader(cb);
    cb.skipBytes(parseFlags.getLength());
}
 
Example 20
Source File: UnSupportedAttribute.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Skip specified bytes in channel buffer.
 *
 * @param cb channelBuffer
 * @param length to be skipped
 */
public static void skipBytes(ChannelBuffer cb, short length) {
    cb.skipBytes(length);
}