8dc6206814b75c81f7b098fd5306c6aa981b7e39
[bgpcep.git] / bgp / extensions / flowspec / src / main / java / org / opendaylight / protocol / bgp / flowspec / AbstractFlowspecNlriParser.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bgp.flowspec;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Joiner;
14 import com.google.common.base.Preconditions;
15 import io.netty.buffer.ByteBuf;
16 import io.netty.buffer.Unpooled;
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.Optional;
20 import java.util.Set;
21 import java.util.stream.Collectors;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.protocol.bgp.flowspec.handlers.BitmaskOperandParser;
25 import org.opendaylight.protocol.bgp.flowspec.handlers.NumericOneByteOperandParser;
26 import org.opendaylight.protocol.bgp.flowspec.handlers.NumericTwoByteOperandParser;
27 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
28 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
29 import org.opendaylight.protocol.bgp.parser.spi.MultiPathSupportUtil;
30 import org.opendaylight.protocol.bgp.parser.spi.NlriParser;
31 import org.opendaylight.protocol.bgp.parser.spi.NlriSerializer;
32 import org.opendaylight.protocol.bgp.parser.spi.PathIdUtil;
33 import org.opendaylight.protocol.bgp.parser.spi.PeerSpecificParserConstraint;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.Dscp;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.Fragment;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.Flowspec;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.FlowspecBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.FlowspecType;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.DestinationPortCase;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.DestinationPortCaseBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.DscpCase;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.DscpCaseBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.FragmentCase;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.FragmentCaseBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.IcmpCodeCase;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.IcmpCodeCaseBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.IcmpTypeCase;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.IcmpTypeCaseBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.PacketLengthCase;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.PacketLengthCaseBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.PortCase;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.PortCaseBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.SourcePortCase;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.SourcePortCaseBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.TcpFlagsCase;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.TcpFlagsCaseBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.destination.port._case.DestinationPorts;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.destination.port._case.DestinationPortsBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.dscp._case.Dscps;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.dscp._case.DscpsBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.fragment._case.Fragments;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.fragment._case.FragmentsBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.icmp.code._case.Codes;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.icmp.code._case.CodesBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.icmp.type._case.Types;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.icmp.type._case.TypesBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.packet.length._case.PacketLengths;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.packet.length._case.PacketLengthsBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.port._case.Ports;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.port._case.PortsBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.source.port._case.SourcePorts;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.source.port._case.SourcePortsBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.tcp.flags._case.TcpFlags;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.flowspec.flowspec.type.tcp.flags._case.TcpFlagsBuilder;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.group.ipv4.flowspec.flowspec.type.DestinationPrefixCase;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev180329.flowspec.destination.group.ipv4.flowspec.flowspec.type.SourcePrefixCase;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.PathId;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes1;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes2;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.destination.DestinationType;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlriBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlriBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutes;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutes;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.AddressFamily;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.SubsequentAddressFamily;
90 import org.opendaylight.yangtools.yang.common.QName;
91 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
92 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
93 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
94 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
95 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
96 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
97 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
98 import org.slf4j.Logger;
99 import org.slf4j.LoggerFactory;
100
101 public abstract class AbstractFlowspecNlriParser implements NlriParser, NlriSerializer {
102     private static final Logger LOG = LoggerFactory.getLogger(AbstractFlowspecNlriParser.class);
103
104     @VisibleForTesting
105     static final NodeIdentifier FLOWSPEC_NID = new NodeIdentifier(Flowspec.QNAME);
106     @VisibleForTesting
107     static final NodeIdentifier FLOWSPEC_TYPE_NID = new NodeIdentifier(FlowspecType.QNAME);
108     public static final NodeIdentifier DEST_PREFIX_NID
109             = new NodeIdentifier(QName.create(DestinationPrefixCase.QNAME, "destination-prefix").intern());
110     public static final NodeIdentifier SOURCE_PREFIX_NID
111             = new NodeIdentifier(QName.create(SourcePrefixCase.QNAME, "source-prefix").intern());
112     @VisibleForTesting
113     static final NodeIdentifier PORTS_NID = new NodeIdentifier(Ports.QNAME);
114     @VisibleForTesting
115     static final NodeIdentifier DEST_PORT_NID = new NodeIdentifier(DestinationPorts.QNAME);
116     @VisibleForTesting
117     static final NodeIdentifier SOURCE_PORT_NID = new NodeIdentifier(SourcePorts.QNAME);
118     @VisibleForTesting
119     static final NodeIdentifier ICMP_TYPE_NID = new NodeIdentifier(Types.QNAME);
120     @VisibleForTesting
121     static final NodeIdentifier ICMP_CODE_NID = new NodeIdentifier(Codes.QNAME);
122     @VisibleForTesting
123     static final NodeIdentifier TCP_FLAGS_NID = new NodeIdentifier(TcpFlags.QNAME);
124     @VisibleForTesting
125     static final NodeIdentifier PACKET_LENGTHS_NID = new NodeIdentifier(PacketLengths.QNAME);
126     @VisibleForTesting
127     static final NodeIdentifier DSCP_NID = new NodeIdentifier(Dscps.QNAME);
128     @VisibleForTesting
129     static final NodeIdentifier FRAGMENT_NID = new NodeIdentifier(Fragments.QNAME);
130     @VisibleForTesting
131     public static final NodeIdentifier OP_NID
132             = new NodeIdentifier(QName.create(Flowspec.QNAME.getModule(), "op"));
133     @VisibleForTesting
134     public static final NodeIdentifier VALUE_NID
135             = new NodeIdentifier(QName.create(Flowspec.QNAME.getModule(), "value"));
136
137     protected final SimpleFlowspecTypeRegistry flowspecTypeRegistry;
138
139     /**
140      * Add this constant to length value to achieve all ones in the leftmost nibble.
141      */
142     private static final int LENGTH_MAGIC = 61440;
143     private static final int MAX_NLRI_LENGTH = 0xFFF;
144     private static final int MAX_NLRI_LENGTH_ONE_BYTE = 0xF0;
145
146     @VisibleForTesting
147     static final String DO_NOT_VALUE = "do-not";
148     @VisibleForTesting
149     static final String FIRST_VALUE = "first";
150     @VisibleForTesting
151     static final String LAST_VALUE = "last";
152     @VisibleForTesting
153     static final String IS_A_VALUE = "is-a";
154
155     private static final String FLOW_SEPARATOR = " AND ";
156
157     protected AbstractFlowspecNlriParser(final SimpleFlowspecTypeRegistry flowspecTypeRegistry) {
158         this.flowspecTypeRegistry = requireNonNull(flowspecTypeRegistry);
159     }
160
161     protected abstract void serializeMpReachNlri(DestinationType dstType, ByteBuf byteAggregator);
162
163     protected abstract void serializeMpUnreachNlri(DestinationType dstType, ByteBuf byteAggregator);
164
165     public abstract void extractSpecificFlowspec(ChoiceNode fsType, FlowspecBuilder fsBuilder);
166
167     protected abstract void stringSpecificFSNlriType(FlowspecType value, StringBuilder buffer);
168
169     /**
170      * Create withdrawn destination type.
171      *
172      * @param nlriFields a list of NLRI fields to be included in the destination type
173      * @param pathId     associated path id with given NLRI
174      * @return created destination type
175      */
176     public abstract DestinationType createWithdrawnDestinationType(Object @NonNull[] nlriFields,
177             @Nullable PathId pathId);
178
179     /**
180      * Create advertized destination type.
181      *
182      * @param nlriFields a list of NLRI fields to be included in the destination type
183      * @param pathId     associated path id with given NLRI
184      * @return created destination type
185      */
186     public abstract DestinationType createAdvertizedRoutesDestinationType(Object @NonNull[] nlriFields,
187             @Nullable PathId pathId);
188
189     @Override
190     public final void serializeAttribute(final Attributes pathAttributes, final ByteBuf byteAggregator) {
191         final Attributes1 pathAttributes1 = pathAttributes.augmentation(Attributes1.class);
192         final Attributes2 pathAttributes2 = pathAttributes.augmentation(Attributes2.class);
193
194         if (pathAttributes1 != null) {
195             final AdvertizedRoutes routes = pathAttributes1.getMpReachNlri().getAdvertizedRoutes();
196             if (routes != null) {
197                 serializeMpReachNlri(routes.getDestinationType(), byteAggregator);
198             }
199         }
200
201         if (pathAttributes2 != null) {
202             final WithdrawnRoutes routes = pathAttributes2.getMpUnreachNlri().getWithdrawnRoutes();
203             if (routes != null) {
204                 serializeMpUnreachNlri(routes.getDestinationType(), byteAggregator);
205             }
206         }
207     }
208
209     protected void serializeNlri(final Object @NonNull [] nlriFields, final @NonNull ByteBuf buffer) {
210         final List<Flowspec> flowspecList = (List<Flowspec>) nlriFields[0];
211         serializeNlri(flowspecList, buffer);
212     }
213
214     protected final void serializeNlri(final List<Flowspec> flowspecList, final @NonNull ByteBuf buffer) {
215         if (flowspecList != null) {
216             for (final Flowspec flow : flowspecList) {
217                 this.flowspecTypeRegistry.serializeFlowspecType(flow.getFlowspecType(), buffer);
218             }
219         }
220     }
221
222     /**
223      * Serializes Flowspec NLRI to ByteBuf.
224      *
225      * @param nlriFields NLRI fields to be serialized
226      * @param pathId path ID
227      * @param buffer where flowspec NLRI will be serialized
228      */
229     protected final void serializeNlri(final Object @NonNull[] nlriFields, final @Nullable PathId pathId,
230             final @NonNull ByteBuf buffer) {
231         final ByteBuf nlriByteBuf = Unpooled.buffer();
232         PathIdUtil.writePathId(pathId, buffer);
233
234         serializeNlri(nlriFields, nlriByteBuf);
235
236         Preconditions.checkState(nlriByteBuf.readableBytes() <= MAX_NLRI_LENGTH,
237                 "Maximum length of Flowspec NLRI reached.");
238         if (nlriByteBuf.readableBytes() <= MAX_NLRI_LENGTH_ONE_BYTE) {
239             buffer.writeByte(nlriByteBuf.readableBytes());
240         } else {
241             buffer.writeShort(nlriByteBuf.readableBytes() + LENGTH_MAGIC);
242         }
243         buffer.writeBytes(nlriByteBuf);
244     }
245
246     public String stringNlri(final DataContainerNode<?> flowspec) {
247         return stringNlri(extractFlowspec(flowspec));
248     }
249
250     protected final String stringNlri(final List<Flowspec> flows) {
251         final StringBuilder buffer = new StringBuilder("all packets ");
252         final Joiner joiner = Joiner.on(FLOW_SEPARATOR);
253         joiner.appendTo(buffer, flows.stream().map(this::encodeFlow).collect(Collectors.toList()));
254         return buffer.toString().replace("  ", " ");
255     }
256
257     public final List<Flowspec> extractFlowspec(final DataContainerNode<?> route) {
258         requireNonNull(route, "Cannot extract flowspec from null route.");
259         final List<Flowspec> fsList = new ArrayList<>();
260         final Optional<DataContainerChild<? extends PathArgument, ?>> flowspecs = route.getChild(FLOWSPEC_NID);
261         if (flowspecs.isPresent()) {
262             for (final UnkeyedListEntryNode flowspec : ((UnkeyedListNode) flowspecs.get()).getValue()) {
263                 final FlowspecBuilder fsBuilder = new FlowspecBuilder();
264                 final Optional<DataContainerChild<?, ?>> flowspecType = flowspec.getChild(FLOWSPEC_TYPE_NID);
265                 if (flowspecType.isPresent()) {
266                     final ChoiceNode fsType = (ChoiceNode) flowspecType.get();
267                     processFlowspecType(fsType, fsBuilder);
268                 }
269                 fsList.add(fsBuilder.build());
270             }
271         }
272         return fsList;
273     }
274
275     private void processFlowspecType(final ChoiceNode fsType, final FlowspecBuilder fsBuilder) {
276         if (fsType.getChild(PORTS_NID).isPresent()) {
277             fsBuilder.setFlowspecType(new PortCaseBuilder()
278                     .setPorts(createPorts((UnkeyedListNode) fsType.getChild(PORTS_NID).get())).build());
279         } else if (fsType.getChild(DEST_PORT_NID).isPresent()) {
280             fsBuilder.setFlowspecType(new DestinationPortCaseBuilder()
281                     .setDestinationPorts(createDestinationPorts((UnkeyedListNode) fsType.getChild(DEST_PORT_NID).get()))
282                     .build());
283         } else if (fsType.getChild(SOURCE_PORT_NID).isPresent()) {
284             fsBuilder.setFlowspecType(new SourcePortCaseBuilder()
285                     .setSourcePorts(createSourcePorts((UnkeyedListNode) fsType.getChild(SOURCE_PORT_NID).get()))
286                     .build());
287         } else if (fsType.getChild(ICMP_TYPE_NID).isPresent()) {
288             fsBuilder.setFlowspecType(new IcmpTypeCaseBuilder()
289                     .setTypes(createTypes((UnkeyedListNode) fsType.getChild(ICMP_TYPE_NID).get())).build());
290         } else if (fsType.getChild(ICMP_CODE_NID).isPresent()) {
291             fsBuilder.setFlowspecType(new IcmpCodeCaseBuilder()
292                     .setCodes(createCodes((UnkeyedListNode) fsType.getChild(ICMP_CODE_NID).get())).build());
293         } else if (fsType.getChild(TCP_FLAGS_NID).isPresent()) {
294             fsBuilder.setFlowspecType(new TcpFlagsCaseBuilder()
295                     .setTcpFlags(createTcpFlags((UnkeyedListNode) fsType.getChild(TCP_FLAGS_NID).get())).build());
296         } else if (fsType.getChild(PACKET_LENGTHS_NID).isPresent()) {
297             fsBuilder.setFlowspecType(new PacketLengthCaseBuilder()
298                     .setPacketLengths(createPacketLengths((UnkeyedListNode) fsType.getChild(PACKET_LENGTHS_NID).get()))
299                     .build());
300         } else if (fsType.getChild(DSCP_NID).isPresent()) {
301             fsBuilder.setFlowspecType(new DscpCaseBuilder()
302                     .setDscps(createDscpsLengths((UnkeyedListNode) fsType.getChild(DSCP_NID).get())).build());
303         } else if (fsType.getChild(FRAGMENT_NID).isPresent()) {
304             fsBuilder.setFlowspecType(new FragmentCaseBuilder()
305                     .setFragments(createFragments((UnkeyedListNode) fsType.getChild(FRAGMENT_NID).get())).build());
306         } else {
307             extractSpecificFlowspec(fsType, fsBuilder);
308         }
309     }
310
311     private static List<Ports> createPorts(final UnkeyedListNode portsData) {
312         final List<Ports> ports = new ArrayList<>();
313
314         for (final UnkeyedListEntryNode node : portsData.getValue()) {
315             final PortsBuilder portsBuilder = new PortsBuilder();
316             node.getChild(OP_NID).ifPresent(
317                 dataContainerChild -> portsBuilder.setOp(NumericTwoByteOperandParser.INSTANCE.create(
318                     (Set<String>) dataContainerChild.getValue())));
319             final Optional<DataContainerChild<? extends PathArgument, ?>> valueNode = node.getChild(VALUE_NID);
320             valueNode.ifPresent(dataContainerChild -> portsBuilder.setValue((Integer) dataContainerChild.getValue()));
321             ports.add(portsBuilder.build());
322         }
323
324         return ports;
325     }
326
327     private static List<DestinationPorts> createDestinationPorts(final UnkeyedListNode destinationPortsData) {
328         final List<DestinationPorts> destinationPorts = new ArrayList<>();
329
330         for (final UnkeyedListEntryNode node : destinationPortsData.getValue()) {
331             final DestinationPortsBuilder destPortsBuilder = new DestinationPortsBuilder();
332             node.getChild(OP_NID).ifPresent(dataContainerChild -> destPortsBuilder.setOp(
333                 NumericTwoByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.getValue())));
334             node.getChild(VALUE_NID).ifPresent(
335                 dataContainerChild -> destPortsBuilder.setValue((Integer) dataContainerChild.getValue()));
336             destinationPorts.add(destPortsBuilder.build());
337         }
338
339         return destinationPorts;
340     }
341
342     private static List<SourcePorts> createSourcePorts(final UnkeyedListNode sourcePortsData) {
343         final List<SourcePorts> sourcePorts = new ArrayList<>();
344
345         for (final UnkeyedListEntryNode node : sourcePortsData.getValue()) {
346             final SourcePortsBuilder sourcePortsBuilder = new SourcePortsBuilder();
347             node.getChild(OP_NID).ifPresent(dataContainerChild -> sourcePortsBuilder.setOp(
348                 NumericTwoByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.getValue())));
349             node.getChild(VALUE_NID).ifPresent(
350                 dataContainerChild -> sourcePortsBuilder.setValue((Integer) dataContainerChild.getValue()));
351             sourcePorts.add(sourcePortsBuilder.build());
352         }
353
354         return sourcePorts;
355     }
356
357     private static List<Types> createTypes(final UnkeyedListNode typesData) {
358         final List<Types> types = new ArrayList<>();
359
360         for (final UnkeyedListEntryNode node : typesData.getValue()) {
361             final TypesBuilder typesBuilder = new TypesBuilder();
362             node.getChild(OP_NID).ifPresent(dataContainerChild -> typesBuilder.setOp(
363                 NumericOneByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.getValue())));
364             final Optional<DataContainerChild<? extends PathArgument, ?>> valueNode = node.getChild(VALUE_NID);
365             valueNode.ifPresent(dataContainerChild -> typesBuilder.setValue((Short) dataContainerChild.getValue()));
366             types.add(typesBuilder.build());
367         }
368
369         return types;
370     }
371
372     private static List<Codes> createCodes(final UnkeyedListNode codesData) {
373         final List<Codes> codes = new ArrayList<>();
374
375         for (final UnkeyedListEntryNode node : codesData.getValue()) {
376             final CodesBuilder codesBuilder = new CodesBuilder();
377             final Optional<DataContainerChild<? extends PathArgument, ?>> opValue = node.getChild(OP_NID);
378             opValue.ifPresent(dataContainerChild -> codesBuilder.setOp(NumericOneByteOperandParser
379                     .INSTANCE.create((Set<String>) dataContainerChild.getValue())));
380             final Optional<DataContainerChild<? extends PathArgument, ?>> valueNode = node.getChild(VALUE_NID);
381             valueNode.ifPresent(dataContainerChild -> codesBuilder.setValue((Short) dataContainerChild.getValue()));
382             codes.add(codesBuilder.build());
383         }
384
385         return codes;
386     }
387
388     private static List<TcpFlags> createTcpFlags(final UnkeyedListNode tcpFlagsData) {
389         final List<TcpFlags> tcpFlags = new ArrayList<>();
390
391         for (final UnkeyedListEntryNode node : tcpFlagsData.getValue()) {
392             final TcpFlagsBuilder tcpFlagsBuilder = new TcpFlagsBuilder();
393             node.getChild(OP_NID).ifPresent(dataContainerChild -> tcpFlagsBuilder
394                     .setOp(BitmaskOperandParser.INSTANCE.create((Set<String>) dataContainerChild.getValue())));
395             node.getChild(VALUE_NID).ifPresent(
396                 dataContainerChild -> tcpFlagsBuilder.setValue((Integer) dataContainerChild.getValue()));
397             tcpFlags.add(tcpFlagsBuilder.build());
398         }
399
400         return tcpFlags;
401     }
402
403     private static List<PacketLengths> createPacketLengths(final UnkeyedListNode packetLengthsData) {
404         final List<PacketLengths> packetLengths = new ArrayList<>();
405
406         for (final UnkeyedListEntryNode node : packetLengthsData.getValue()) {
407             final PacketLengthsBuilder packetLengthsBuilder = new PacketLengthsBuilder();
408             node.getChild(OP_NID).ifPresent(dataContainerChild -> packetLengthsBuilder.setOp(
409                 NumericTwoByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.getValue())));
410             node.getChild(VALUE_NID).ifPresent(
411                 dataContainerChild -> packetLengthsBuilder.setValue((Integer) dataContainerChild.getValue()));
412             packetLengths.add(packetLengthsBuilder.build());
413         }
414
415         return packetLengths;
416     }
417
418     private static List<Dscps> createDscpsLengths(final UnkeyedListNode dscpLengthsData) {
419         final List<Dscps> dscpsLengths = new ArrayList<>();
420
421         for (final UnkeyedListEntryNode node : dscpLengthsData.getValue()) {
422             final DscpsBuilder dscpsLengthsBuilder = new DscpsBuilder();
423             node.getChild(OP_NID).ifPresent(dataContainerChild -> dscpsLengthsBuilder.setOp(
424                 NumericOneByteOperandParser.INSTANCE.create((Set<String>) dataContainerChild.getValue())));
425             node.getChild(VALUE_NID).ifPresent(
426                 dataContainerChild -> dscpsLengthsBuilder.setValue(new Dscp((Short) dataContainerChild.getValue())));
427             dscpsLengths.add(dscpsLengthsBuilder.build());
428         }
429
430         return dscpsLengths;
431     }
432
433     private static List<Fragments> createFragments(final UnkeyedListNode fragmentsData) {
434         final List<Fragments> fragments = new ArrayList<>();
435
436         for (final UnkeyedListEntryNode node : fragmentsData.getValue()) {
437             final FragmentsBuilder fragmentsBuilder = new FragmentsBuilder();
438             node.getChild(OP_NID).ifPresent(dataContainerChild -> fragmentsBuilder.setOp(
439                 BitmaskOperandParser.INSTANCE.create((Set<String>) dataContainerChild.getValue())));
440             node.getChild(VALUE_NID).ifPresent(dataContainerChild -> fragmentsBuilder.setValue(
441                 createFragment((Set<String>) dataContainerChild.getValue())));
442             fragments.add(fragmentsBuilder.build());
443         }
444
445         return fragments;
446     }
447
448     private static Fragment createFragment(final Set<String> data) {
449         return new Fragment(data.contains(DO_NOT_VALUE), data.contains(FIRST_VALUE), data.contains(IS_A_VALUE),
450                 data.contains(LAST_VALUE));
451     }
452
453     @VisibleForTesting
454     final String encodeFlow(final Flowspec flow) {
455         final StringBuilder buffer = new StringBuilder();
456         final FlowspecType value = flow.getFlowspecType();
457         if (value instanceof PortCase) {
458             buffer.append("where port ");
459             buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(((PortCase) value).getPorts()));
460         } else if (value instanceof DestinationPortCase) {
461             buffer.append("where destination port ");
462             buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(
463                 ((DestinationPortCase) value).getDestinationPorts()));
464         } else if (value instanceof SourcePortCase) {
465             buffer.append("where source port ");
466             buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(((SourcePortCase) value).getSourcePorts()));
467         } else if (value instanceof IcmpTypeCase) {
468             buffer.append("where ICMP type ");
469             buffer.append(NumericOneByteOperandParser.INSTANCE.toString(((IcmpTypeCase) value).getTypes()));
470         } else if (value instanceof IcmpCodeCase) {
471             buffer.append("where ICMP code ");
472             buffer.append(NumericOneByteOperandParser.INSTANCE.toString(((IcmpCodeCase) value).getCodes()));
473         } else if (value instanceof TcpFlagsCase) {
474             buffer.append(stringTcpFlags(((TcpFlagsCase) value).getTcpFlags()));
475         } else if (value instanceof PacketLengthCase) {
476             buffer.append("where packet length ");
477             buffer.append(NumericTwoByteOperandParser.INSTANCE.toString(((PacketLengthCase) value).getPacketLengths()));
478         } else if (value instanceof DscpCase) {
479             buffer.append(stringDscp(((DscpCase) value).getDscps()));
480         } else if (value instanceof FragmentCase) {
481             buffer.append(stringFragment(((FragmentCase) value).getFragments()));
482         } else {
483             stringSpecificFSNlriType(value, buffer);
484         }
485         return buffer.toString();
486     }
487
488     private static String stringTcpFlags(final List<TcpFlags> flags) {
489         final StringBuilder buffer = new StringBuilder("where TCP flags ");
490         boolean isFirst = true;
491         for (final TcpFlags item : flags) {
492             buffer.append(BitmaskOperandParser.INSTANCE.toString(item.getOp(), isFirst));
493             buffer.append(item.getValue());
494             buffer.append(' ');
495             if (isFirst) {
496                 isFirst = false;
497             }
498         }
499         return buffer.toString();
500     }
501
502     private static String stringDscp(final List<Dscps> dscps) {
503         final StringBuilder buffer = new StringBuilder("where DSCP ");
504         boolean isFirst = true;
505         for (final Dscps item : dscps) {
506             buffer.append(NumericOneByteOperandParser.INSTANCE.toString(item.getOp(), isFirst));
507             buffer.append(item.getValue().getValue());
508             buffer.append(' ');
509             if (isFirst) {
510                 isFirst = false;
511             }
512         }
513         return buffer.toString();
514     }
515
516     private static String stringFragment(final List<Fragments> fragments) {
517         final StringBuilder buffer = new StringBuilder("where fragment ");
518         boolean isFirst = true;
519         for (final Fragments item : fragments) {
520             buffer.append(BitmaskOperandParser.INSTANCE.toString(item.getOp(), isFirst));
521             buffer.append(stringFragment(item.getValue()));
522             if (isFirst) {
523                 isFirst = false;
524             }
525         }
526         return buffer.toString();
527     }
528
529     private static String stringFragment(final Fragment fragment) {
530         final StringBuilder buffer = new StringBuilder();
531         if (fragment.isDoNot()) {
532             buffer.append("'DO NOT' ");
533         }
534         if (fragment.isFirst()) {
535             buffer.append("'IS FIRST' ");
536         }
537         if (fragment.isLast()) {
538             buffer.append("'IS LAST' ");
539         }
540         if (fragment.isIsA()) {
541             buffer.append("'IS A' ");
542         }
543         return buffer.toString();
544     }
545
546     public static int readNlriLength(final @NonNull ByteBuf nlri) {
547         requireNonNull(nlri, "NLRI information cannot be null");
548         Preconditions.checkState(nlri.isReadable(), "NLRI Byte buffer is not readable.");
549         int length = nlri.readUnsignedByte();
550         if (length >= MAX_NLRI_LENGTH_ONE_BYTE) {
551             length = (length << Byte.SIZE | nlri.readUnsignedByte()) & MAX_NLRI_LENGTH;
552         }
553         Preconditions.checkState(length > 0 && length <= nlri.readableBytes(),
554                 "Invalid flowspec NLRI length %s", length);
555         return length;
556     }
557
558     /**
559      * Parses Flowspec NLRI into list of Flowspec.
560      *
561      * @param nlri byte representation of NLRI which will be parsed
562      * @return list of Flowspec
563      */
564     protected final List<Flowspec> parseNlriFlowspecList(final @NonNull ByteBuf nlri) {
565         if (!nlri.isReadable()) {
566             return null;
567         }
568         final List<Flowspec> fss = new ArrayList<>();
569
570         while (nlri.isReadable()) {
571             int nlriLength = readNlriLength(nlri);
572             Preconditions.checkState(nlriLength > 0 && nlriLength <= nlri.readableBytes(),
573                     "Invalid flowspec NLRI length %s", nlriLength);
574             LOG.trace("Flowspec NLRI length is {}", nlriLength);
575
576             while (nlriLength > 0) {
577                 final int readableLength = nlri.readableBytes();
578                 final FlowspecBuilder builder = new FlowspecBuilder();
579                 builder.setFlowspecType(this.flowspecTypeRegistry.parseFlowspecType(nlri));
580                 fss.add(builder.build());
581                 final int flowspecTypeLength = readableLength - nlri.readableBytes();
582                 nlriLength -= flowspecTypeLength;
583             }
584             Preconditions.checkState(nlriLength == 0,
585                     "Remain NLRI length should be 0 instead of %s", nlriLength);
586         }
587
588         return fss;
589     }
590
591     /**
592      * Override this function to parse additional NLRI fields.
593      *
594      * @param nlri NLRI buffer
595      * @return Parsed additional fields
596      */
597     protected Object @NonNull[] parseNlri(final @NonNull ByteBuf nlri) throws BGPParsingException {
598         return new Object[] {parseNlriFlowspecList(nlri)};
599     }
600
601     @Override
602     public final void parseNlri(final @NonNull ByteBuf nlri, final @NonNull MpReachNlriBuilder builder,
603             final PeerSpecificParserConstraint constraint) throws BGPParsingException {
604         if (!nlri.isReadable()) {
605             return;
606         }
607         final PathId pathId = readPathId(nlri, builder.getAfi(), builder.getSafi(), constraint);
608         final Object[] nlriFields = parseNlri(nlri);
609         builder.setAdvertizedRoutes(
610             new AdvertizedRoutesBuilder()
611                 .setDestinationType(
612                     createAdvertizedRoutesDestinationType(nlriFields, pathId)
613                 ).build()
614         );
615     }
616
617     @Override
618     public final void parseNlri(final @NonNull ByteBuf nlri, final @NonNull MpUnreachNlriBuilder builder,
619             final PeerSpecificParserConstraint constraint) throws BGPParsingException {
620         if (!nlri.isReadable()) {
621             return;
622         }
623         final PathId pathId = readPathId(nlri, builder.getAfi(), builder.getSafi(), constraint);
624         final Object[] nlriFields = parseNlri(nlri);
625         builder.setWithdrawnRoutes(
626             new WithdrawnRoutesBuilder()
627                 .setDestinationType(
628                     createWithdrawnDestinationType(nlriFields, pathId)
629                 ).build()
630         );
631     }
632
633     protected static @Nullable PathId readPathId(final @NonNull ByteBuf nlri, final Class<? extends AddressFamily> afi,
634             final Class<? extends SubsequentAddressFamily> safi, final PeerSpecificParserConstraint constraint) {
635         if (MultiPathSupportUtil.isTableTypeSupported(constraint, new BgpTableTypeImpl(afi, safi))) {
636             return PathIdUtil.readPathId(nlri);
637         }
638         return null;
639     }
640 }
641