List of usage examples for io.netty.buffer ByteBuf readUnsignedShort
public abstract int readUnsignedShort();
From source file:io.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();//from w ww. j a va 2 s. co 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 read = in.readerIndex() - start; while (read < message.getRemainingLength()) { decodeSubscription(in, message); read = in.readerIndex() - start; } if (message.subscriptions().isEmpty()) { throw new CorruptedFrameException("subscribe MUST have got at least 1 couple topic/QoS"); } out.add(message); }
From source file:io.netlibs.bgp.handlers.BGPv4Reframer.java
License:Apache License
/** * reframe the received packet to completely contain the next BGPv4 packet. It peeks into the first four bytes of the TCP stream which * contain a 16-bit marker and a 16-bit length field. The marker must be all one's and the length value must be between 19 and 4096 * according to RFC 4271. The marker and length constraints are verified and if either is violated the connection is closed early. * /*w w w . j a v a 2 s . co m*/ * Any packets that are added start on the type byte. The buffer will contain the full message payload. * */ @Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf buffer, final List<Object> out) throws Exception { if (buffer.readableBytes() < (BGPv4Constants.BGP_PACKET_MIN_LENGTH - 1)) { // need more bytes for a full read. return; } buffer.markReaderIndex(); // confirm that the next BGP_PACKET_MARKER_LENGTH bytes are all 0xff. if (buffer.forEachByte(buffer.readerIndex(), BGPv4Constants.BGP_PACKET_MARKER_LENGTH, value -> value == (byte) 0xff) != -1) { log.error("received invalid marker, closing connection"); NotificationHelper.sendEncodedNotification(ctx, new ConnectionNotSynchronizedNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } // skip the marker. buffer.skipBytes(BGPv4Constants.BGP_PACKET_MARKER_LENGTH); // read the packet length. final int length = buffer.readUnsignedShort(); if ((length < BGPv4Constants.BGP_PACKET_MIN_LENGTH) || (length > BGPv4Constants.BGP_PACKET_MAX_LENGTH)) { log.error("received illegal packet size {}, must be between {} and {}. closing connection", new Object[] { length, BGPv4Constants.BGP_PACKET_MIN_LENGTH, BGPv4Constants.BGP_PACKET_MAX_LENGTH }); NotificationHelper.sendEncodedNotification(ctx, new BadMessageLengthNotificationPacket(length), new BgpEventFireChannelFutureListener(ctx)); return; } final int mustRead = (length - (BGPv4Constants.BGP_PACKET_MARKER_LENGTH + 2)); // we have consumed marker and length at this point // must if we don't have the right amount, abort. if (buffer.readableBytes() < mustRead) { buffer.resetReaderIndex(); return; } out.add(buffer.readBytes(mustRead)); }
From source file:io.netlibs.bgp.netty.codec.OpenPacketDecoder.java
License:Apache License
/** * decode the OPEN network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet. * * @param buffer//from ww w . j a v a 2 s.c o m * the buffer containing the data. * @return */ public NotificationPacket decodeOpenNotificationPacket(final ByteBuf buffer, final int errorSubcode) { NotificationPacket packet = null; switch (errorSubcode) { case OpenNotificationPacket.SUBCODE_BAD_BGP_IDENTIFIER: packet = new BadBgpIdentifierNotificationPacket(); break; case OpenNotificationPacket.SUBCODE_BAD_PEER_AS: packet = new BadPeerASNotificationPacket(); break; case OpenNotificationPacket.SUBCODE_UNACCEPTABLE_HOLD_TIMER: packet = new UnacceptableHoldTimerNotificationPacket(); break; case OpenNotificationPacket.SUBCODE_UNSPECIFIC: packet = new UnspecificOpenNotificationPacket(); break; case OpenNotificationPacket.SUBCODE_UNSUPPORTED_OPTIONAL_PARAMETER: packet = new UnsupportedOptionalParameterNotificationPacket(); break; case OpenNotificationPacket.SUBCODE_UNSUPPORTED_VERSION_NUMBER: packet = new UnsupportedVersionNumberNotificationPacket(buffer.readUnsignedShort()); break; case OpenNotificationPacket.SUBCODE_UNSUPPORTED_CAPABILITY: packet = new CapabilityListUnsupportedCapabilityNotificationPacket( CapabilityCodec.decodeCapabilities(buffer)); break; } return packet; }
From source file:io.netlibs.bgp.netty.codec.OpenPacketDecoder.java
License:Apache License
/** * decode the OPEN network packet. The passed channel buffer MUST point to the first packet octet AFTER the packet type and the buffer * must be at least 9 octets large at this point. * * @param buffer//from ww w. ja v a 2 s .c o m * the buffer containing the data. * @return */ public OpenPacket decodeOpenPacket(final ByteBuf buffer) { OpenPacketBuilder b = OpenPacket.builder(); ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_OPEN, -1); short version = buffer.readUnsignedByte(); if (version != BGPv4Constants.BGP_VERSION) { throw new UnsupportedVersionNumberException(BGPv4Constants.BGP_VERSION); } b.protocolVersion(version); b.autonomousSystem(buffer.readUnsignedShort()); b.holdTime(buffer.readUnsignedShort()); long identifier = buffer.readUnsignedInt(); if ((identifier & IPV4_MULTICAST_MASK) == IPV4_MULTICAST_MASK) { throw new BadBgpIdentifierException(); } b.bgpIdentifier(identifier); final int parameterLength = buffer.readUnsignedByte(); if (parameterLength > 0) { while (buffer.isReadable()) { final int parameterType = buffer.readUnsignedByte(); final int paramLength = buffer.readUnsignedByte(); final ByteBuf valueBuffer = Unpooled.buffer(paramLength); buffer.readBytes(valueBuffer); switch (parameterType) { case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_AUTH: log.warn("Ignoring auth parameter"); // RFC 4271 says auth is deprecated. break; case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_CAPABILITY: b.capabilities(CapabilityCodec.decodeCapabilities(valueBuffer)); break; default: throw new UnsupportedOptionalParameterException(); } } } return b.build(); }
From source file:io.netlibs.bgp.netty.codec.RouteRefreshPacketDecoder.java
License:Apache License
/** * decode the REFRESH network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet. * /*from w w w. j ava2 s . com*/ * @param buffer * the buffer containing the data. * * @return the decoded packet or null on decoding problems. Neither RFC2918 nor RFC5291 nor RFC4271 describe an error handling procedure, * so best advise is to ignore invalid packets for now. */ public BGPv4Packet decodeRouteRefreshPacket(ByteBuf buffer) { RouteRefreshPacket packet = null; try { AddressFamily af = AddressFamily.fromCode(buffer.readUnsignedShort()); buffer.readByte(); // swallow reserved octet SubsequentAddressFamily saf = SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()); packet = new RouteRefreshPacket(af, saf); if (buffer.isReadable()) { // we have outbound router filter rules here OutboundRouteFilter orf = new OutboundRouteFilter(af, saf); orf.setRefreshType(ORFRefreshType.fromCode(buffer.readUnsignedByte())); while (buffer.isReadable()) { ORFType orfType = ORFType.fromCode(buffer.readUnsignedByte()); ByteBuf entriesBuffer = Unpooled.buffer(buffer.readUnsignedShort()); buffer.readBytes(entriesBuffer); orf.addAllORFEntries(decodeORFEntries(entriesBuffer, orfType)); } packet.setOutboundRouteFilter(orf); } } catch (Exception e) { log.error("cannot decode ROUTE_REFRESH packet, suppressing it from further processing", e); packet = null; } return packet; }
From source file:io.netlibs.bgp.netty.codec.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. * * @param buffer/* w w w . j av a2s . c o m*/ * the buffer containing the data. * @return */ public BGPv4Packet decodeUpdatePacket(final ByteBuf buffer) { final UpdatePacket packet = new UpdatePacket(); ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_UPDATE, -1); if (buffer.readableBytes() < 2) { throw new MalformedAttributeListException(); } // handle withdrawn routes final int withdrawnOctets = buffer.readUnsignedShort(); // sanity checking if (withdrawnOctets > buffer.readableBytes()) { throw new MalformedAttributeListException(); } ByteBuf withdrawnBuffer = null; if (withdrawnOctets > 0) { withdrawnBuffer = Unpooled.buffer(withdrawnOctets); buffer.readBytes(withdrawnBuffer); } // sanity checking if (buffer.readableBytes() < 2) { throw new MalformedAttributeListException(); } // handle path attributes final int pathAttributeOctets = buffer.readUnsignedShort(); // sanity checking if (pathAttributeOctets > buffer.readableBytes()) { throw new MalformedAttributeListException(); } ByteBuf pathAttributesBuffer = null; if (pathAttributeOctets > 0) { pathAttributesBuffer = Unpooled.buffer(pathAttributeOctets); buffer.readBytes(pathAttributesBuffer); } if (withdrawnBuffer != null) { try { packet.getWithdrawnRoutes().addAll(this.decodeWithdrawnRoutes(withdrawnBuffer)); } catch (final IndexOutOfBoundsException e) { throw new MalformedAttributeListException(); } } if (pathAttributesBuffer != null) { try { List<PathAttribute> attrs = this.decodePathAttributes(pathAttributesBuffer); packet.getPathAttributes().addAll(attrs); } catch (AttributeLengthException ex) { throw ex; } catch (final IndexOutOfBoundsException ex) { throw new MalformedAttributeListException(); } } // handle network layer reachability information if (buffer.readableBytes() > 0) { try { while (buffer.readableBytes() > 0) { packet.getNlris().add(NLRICodec.decodeNLRI(buffer)); } } catch (final IndexOutOfBoundsException e) { throw new InvalidNetworkFieldException(); } catch (final IllegalArgumentException e) { throw new InvalidNetworkFieldException(); } } return packet; }
From source file:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java
License:Apache License
private ASPathAttribute decodeASPathAttribute(final ByteBuf buffer, final ASType asType) { final ASPathAttribute attr = new ASPathAttribute(asType); while (buffer.isReadable()) { if (buffer.readableBytes() < 2) { throw new MalformedASPathAttributeException(); }/*from w w w. j a v a2 s.c o m*/ final int segmentType = buffer.readUnsignedByte(); final int pathLength = buffer.readUnsignedByte(); final int pathOctetLength = (pathLength * (asType == ASType.AS_NUMBER_4OCTETS ? 4 : 2)); if (buffer.readableBytes() < pathOctetLength) { throw new MalformedASPathAttributeException(); } final PathSegment segment = new PathSegment(asType); try { segment.setPathSegmentType(PathSegmentTypeCodec.fromCode(segmentType)); } catch (final IllegalArgumentException 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:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java
License:Apache License
private AggregatorPathAttribute decodeAggregatorPathAttribute(final ByteBuf buffer, final ASType asType) { final AggregatorPathAttribute attr = new AggregatorPathAttribute(asType); if (buffer.readableBytes() != PathAttributeCodec.valueLength(attr)) { throw new AttributeLengthException(); }// w ww. jav a 2 s.c o m if (asType == ASType.AS_NUMBER_4OCTETS) { attr.setAsNumber((int) buffer.readUnsignedInt()); } else { attr.setAsNumber(buffer.readUnsignedShort()); } try { final byte[] addr = new byte[4]; buffer.readBytes(addr); attr.setAggregator((Inet4Address) InetAddress.getByAddress(addr)); } catch (final UnknownHostException e) { throw new OptionalAttributeErrorException(); } return attr; }
From source file:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java
License:Apache License
private CommunityPathAttribute decodeCommunityPathAttribute(final ByteBuf buffer) { final CommunityPathAttribute attr = new CommunityPathAttribute(); if ((buffer.readableBytes() < 4) || ((buffer.readableBytes() % 4) != 0)) { throw new OptionalAttributeErrorException(); }//from w ww.j av a2 s . c o m while (buffer.isReadable()) { final CommunityMember member = new CommunityMember(); member.setAsNumber(buffer.readUnsignedShort()); member.setValue(buffer.readUnsignedShort()); attr.getMembers().add(member); } return attr; }
From source file:io.netlibs.bgp.netty.codec.UpdatePacketDecoder.java
License:Apache License
private MultiProtocolReachableNLRI decodeMpReachNlriPathAttribute(final ByteBuf buffer) { final MultiProtocolReachableNLRI attr = new MultiProtocolReachableNLRI(); try {/*from w w w . j a va2 s . c om*/ attr.setAddressFamily(AddressFamily.fromCode(buffer.readUnsignedShort())); attr.setSubsequentAddressFamily(SubsequentAddressFamily.fromCode(buffer.readUnsignedByte())); final int nextHopLength = buffer.readUnsignedByte(); if (nextHopLength > 0) { final byte[] nextHop = new byte[nextHopLength]; buffer.readBytes(nextHop); attr.setNextHopAddress(nextHop); } buffer.readByte(); // reserved while (buffer.isReadable()) { attr.getNlris().add(NLRICodec.decodeNLRI(buffer)); } } catch (final RuntimeException e) { throw new OptionalAttributeErrorException(); } return attr; }