Move ipv4/ipv6 ByteBuf utilities to Ipv{4,6}Util
[bgpcep.git] / bgp / parser-impl / src / main / java / org / opendaylight / protocol / bgp / parser / impl / message / BGPUpdateMessageParser.java
1 /*
2  * Copyright (c) 2013 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.parser.impl.message;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Streams;
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 org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
21 import org.opendaylight.protocol.bgp.parser.BGPError;
22 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
23 import org.opendaylight.protocol.bgp.parser.BGPTreatAsWithdrawException;
24 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
25 import org.opendaylight.protocol.bgp.parser.impl.message.update.AsPathAttributeParser;
26 import org.opendaylight.protocol.bgp.parser.impl.message.update.NextHopAttributeParser;
27 import org.opendaylight.protocol.bgp.parser.impl.message.update.OriginAttributeParser;
28 import org.opendaylight.protocol.bgp.parser.spi.AttributeRegistry;
29 import org.opendaylight.protocol.bgp.parser.spi.MessageParser;
30 import org.opendaylight.protocol.bgp.parser.spi.MessageSerializer;
31 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
32 import org.opendaylight.protocol.bgp.parser.spi.MultiPathSupportUtil;
33 import org.opendaylight.protocol.bgp.parser.spi.NlriRegistry;
34 import org.opendaylight.protocol.bgp.parser.spi.ParsedAttributes;
35 import org.opendaylight.protocol.bgp.parser.spi.PathIdUtil;
36 import org.opendaylight.protocol.bgp.parser.spi.PeerSpecificParserConstraint;
37 import org.opendaylight.protocol.bgp.parser.spi.RevisedErrorHandling;
38 import org.opendaylight.protocol.util.Ipv4Util;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.PathId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.UpdateBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.AttributesBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.Nlri;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.NlriBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.WithdrawnRoutes;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.WithdrawnRoutesBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes1;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes2;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes2Builder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.graceful.restart.capability.TablesKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlri;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlri;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv4AddressFamily;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.UnicastSubsequentAddressFamily;
57 import org.opendaylight.yangtools.yang.binding.Notification;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 /**
62  * LENGTH fields, that denote the length of the fields with variable length, have fixed SIZE.
63  *
64  * @see <a href="http://tools.ietf.org/html/rfc4271#section-4.3">BGP-4 Update Message Format</a>
65  */
66 public final class BGPUpdateMessageParser implements MessageParser, MessageSerializer {
67     private static final Logger LOG = LoggerFactory.getLogger(BGPUpdateMessageParser.class);
68
69     public static final int TYPE = 2;
70
71     private final AttributeRegistry attrReg;
72     private final NlriRegistry nlriReg;
73
74     public BGPUpdateMessageParser(final AttributeRegistry attrReg, final NlriRegistry nlriReg) {
75         this.attrReg = requireNonNull(attrReg);
76         this.nlriReg = requireNonNull(nlriReg);
77     }
78
79     @Override
80     public void serializeMessage(final Notification message, final ByteBuf bytes) {
81         checkArgument(message instanceof Update, "Message needs to be of type Update");
82         final Update update = (Update) message;
83
84         final ByteBuf messageBody = Unpooled.buffer();
85         final List<WithdrawnRoutes> withdrawnRoutes = update.getWithdrawnRoutes();
86         if (withdrawnRoutes != null) {
87             final ByteBuf withdrawnRoutesBuf = Unpooled.buffer();
88             withdrawnRoutes.forEach(withdrawnRoute -> writePathIdPrefix(withdrawnRoutesBuf, withdrawnRoute.getPathId(),
89                     withdrawnRoute.getPrefix()));
90             messageBody.writeShort(withdrawnRoutesBuf.writerIndex());
91             messageBody.writeBytes(withdrawnRoutesBuf);
92         } else {
93             messageBody.writeShort(0);
94         }
95         if (update.getAttributes() != null) {
96             final ByteBuf pathAttributesBuf = Unpooled.buffer();
97             this.attrReg.serializeAttribute(update.getAttributes(), pathAttributesBuf);
98             messageBody.writeShort(pathAttributesBuf.writerIndex());
99             messageBody.writeBytes(pathAttributesBuf);
100         } else {
101             messageBody.writeShort(0);
102         }
103         final List<Nlri> nlris = update.getNlri();
104         if (nlris != null) {
105             nlris.forEach(nlri -> writePathIdPrefix(messageBody, nlri.getPathId(), nlri.getPrefix()));
106         }
107         MessageUtil.formatMessage(TYPE, messageBody, bytes);
108     }
109
110     private static void writePathIdPrefix(final ByteBuf byteBuf, final PathId pathId, final Ipv4Prefix ipv4Prefix) {
111         PathIdUtil.writePathId(pathId, byteBuf);
112         Ipv4Util.writeMinimalPrefix(ipv4Prefix, byteBuf);
113     }
114
115     /**
116      * Parse Update message from buffer. Calls {@link #checkMandatoryAttributesPresence(Update, RevisedErrorHandling)}
117      * to check for presence of mandatory attributes.
118      *
119      * @param buffer Encoded BGP message in ByteBuf
120      * @param messageLength Length of the BGP message
121      * @param constraint Peer specific constraints
122      * @return Parsed Update message body
123      */
124     @Override
125     public Update parseMessageBody(final ByteBuf buffer, final int messageLength,
126             final PeerSpecificParserConstraint constraint) throws BGPDocumentedException {
127         checkArgument(buffer != null && buffer.isReadable(),"Buffer cannot be null or empty.");
128
129         final UpdateBuilder builder = new UpdateBuilder();
130         final boolean isMultiPathSupported = MultiPathSupportUtil.isTableTypeSupported(constraint,
131                 new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class));
132         final RevisedErrorHandling errorHandling = RevisedErrorHandling.from(constraint);
133
134         final int withdrawnRoutesLength = buffer.readUnsignedShort();
135         if (withdrawnRoutesLength > 0) {
136             final List<WithdrawnRoutes> withdrawnRoutes = new ArrayList<>();
137             final ByteBuf withdrawnRoutesBuffer = buffer.readBytes(withdrawnRoutesLength);
138             while (withdrawnRoutesBuffer.isReadable()) {
139                 final WithdrawnRoutesBuilder withdrawnRoutesBuilder = new WithdrawnRoutesBuilder();
140                 if (isMultiPathSupported) {
141                     withdrawnRoutesBuilder.setPathId(PathIdUtil.readPathId(withdrawnRoutesBuffer));
142                 }
143                 withdrawnRoutesBuilder.setPrefix(readPrefix(withdrawnRoutesBuffer, errorHandling, "Withdrawn Routes"));
144                 withdrawnRoutes.add(withdrawnRoutesBuilder.build());
145             }
146             withdrawnRoutesBuffer.release();
147             builder.setWithdrawnRoutes(withdrawnRoutes);
148         }
149         final int totalPathAttrLength = buffer.readUnsignedShort();
150         if (withdrawnRoutesLength == 0 && totalPathAttrLength == 0) {
151             return builder.build();
152         }
153
154         Optional<BGPTreatAsWithdrawException> withdrawCauseOpt;
155         if (totalPathAttrLength > 0) {
156             final ParsedAttributes attributes = parseAttributes(buffer, totalPathAttrLength, constraint);
157             builder.setAttributes(attributes.getAttributes());
158             withdrawCauseOpt = attributes.getWithdrawCause();
159         } else {
160             withdrawCauseOpt = Optional.empty();
161         }
162
163         final List<Nlri> nlri = new ArrayList<>();
164         while (buffer.isReadable()) {
165             final NlriBuilder nlriBuilder = new NlriBuilder();
166             if (isMultiPathSupported) {
167                 nlriBuilder.setPathId(PathIdUtil.readPathId(buffer));
168             }
169             nlriBuilder.setPrefix(readPrefix(buffer, errorHandling, "NLRI"));
170             nlri.add(nlriBuilder.build());
171         }
172         if (!nlri.isEmpty()) {
173             builder.setNlri(nlri);
174         }
175
176         try {
177             checkMandatoryAttributesPresence(builder.build(), errorHandling);
178         } catch (BGPTreatAsWithdrawException e) {
179             LOG.debug("Well-known mandatory attributes missing", e);
180             if (withdrawCauseOpt.isPresent()) {
181                 final BGPTreatAsWithdrawException exception = withdrawCauseOpt.get();
182                 exception.addSuppressed(e);
183                 withdrawCauseOpt = Optional.of(exception);
184             } else {
185                 withdrawCauseOpt = Optional.of(e);
186             }
187         }
188
189         Update msg = builder.build();
190         if (withdrawCauseOpt.isPresent()) {
191             // Attempt to apply treat-as-withdraw
192             msg = withdrawUpdate(msg, errorHandling, withdrawCauseOpt.get());
193         }
194
195         LOG.debug("BGP Update message was parsed {}.", msg);
196         return msg;
197     }
198
199     @SuppressWarnings("checkstyle:illegalCatch")
200     private ParsedAttributes parseAttributes(final ByteBuf buffer, final int totalPathAttrLength,
201             final PeerSpecificParserConstraint constraint) throws BGPDocumentedException {
202         try {
203             return attrReg.parseAttributes(buffer.readSlice(totalPathAttrLength), constraint);
204         } catch (final RuntimeException | BGPParsingException e) {
205             // Catch everything else and turn it into a BGPDocumentedException
206             throw new BGPDocumentedException("Could not parse BGP attributes.", BGPError.MALFORMED_ATTR_LIST, e);
207         }
208     }
209
210     private static Ipv4Prefix readPrefix(final ByteBuf buf, final RevisedErrorHandling errorHandling,
211             final String fieldName) throws BGPDocumentedException {
212         final int prefixLength = buf.readUnsignedByte();
213         if (errorHandling != RevisedErrorHandling.NONE) {
214             // https://tools.ietf.org/html/rfc7606#section-5.3
215             if (prefixLength > 32) {
216                 throw new BGPDocumentedException(fieldName + " length " + prefixLength + " exceeds 32 bytes",
217                     BGPError.ATTR_LENGTH_ERROR);
218             }
219             if (prefixLength > buf.readableBytes() * 8) {
220                 throw new BGPDocumentedException(fieldName + " length " + prefixLength
221                     + " exceeds unconsumed field space", BGPError.ATTR_LENGTH_ERROR);
222             }
223         }
224
225         return Ipv4Util.prefixForByteBuf(buf, prefixLength);
226     }
227
228     /**
229      * Check for presence of well known mandatory path attributes ORIGIN, AS_PATH and NEXT_HOP in Update message.
230      *
231      * @param message Update message
232      * @param errorHandling Error handling type
233      */
234     private static void checkMandatoryAttributesPresence(final Update message,
235             final RevisedErrorHandling errorHandling) throws BGPDocumentedException, BGPTreatAsWithdrawException {
236         requireNonNull(message, "Update message cannot be null");
237
238         final Attributes attrs = message.getAttributes();
239         if (message.getNlri() != null && (attrs == null || attrs.getCNextHop() == null)) {
240             throw reportMissingAttribute(errorHandling, "NEXT_HOP", NextHopAttributeParser.TYPE);
241         }
242
243         if (MessageUtil.isAnyNlriPresent(message)) {
244             if (attrs == null || attrs.getOrigin() == null) {
245                 throw reportMissingAttribute(errorHandling, "ORIGIN", OriginAttributeParser.TYPE);
246             }
247             if (attrs.getAsPath() == null) {
248                 throw reportMissingAttribute(errorHandling, "AS_PATH", AsPathAttributeParser.TYPE);
249             }
250         }
251     }
252
253     private static BGPDocumentedException reportMissingAttribute(final RevisedErrorHandling errorHandling,
254             final String attrName, final int attrType) throws BGPDocumentedException, BGPTreatAsWithdrawException {
255         return errorHandling.reportError(BGPError.WELL_KNOWN_ATTR_MISSING, new byte[] { (byte) attrType },
256             "Well known mandatory attribute missing: %s", attrName);
257     }
258
259     private Update withdrawUpdate(final Update parsed, final RevisedErrorHandling errorHandling,
260             final BGPTreatAsWithdrawException withdrawCause) throws BGPDocumentedException {
261         if (errorHandling == RevisedErrorHandling.NONE) {
262             throw new BGPDocumentedException(withdrawCause);
263         }
264
265         // TODO: additional checks as per RFC7606 section 5.2
266
267         LOG.debug("Converting BGP Update message {} to withdraw", parsed, withdrawCause);
268         final UpdateBuilder builder = new UpdateBuilder();
269
270         final List<Nlri> nlris = parsed.getNlri();
271         final List<WithdrawnRoutes> withdrawn;
272         if (nlris != null && !nlris.isEmpty()) {
273             withdrawn = Streams.concat(parsed.nonnullWithdrawnRoutes().stream(),
274                 nlris.stream().map(nlri -> new WithdrawnRoutesBuilder(nlri).build()))
275                     .collect(ImmutableList.toImmutableList());
276         } else {
277             withdrawn = parsed.getWithdrawnRoutes();
278         }
279         builder.setWithdrawnRoutes(withdrawn);
280
281         final Attributes attributes = parsed.getAttributes();
282         if (attributes != null) {
283             builder.setAttributes(withdrawAttributes(attributes, withdrawCause));
284         }
285
286         return builder.build();
287     }
288
289     private Attributes withdrawAttributes(final Attributes parsed,
290             final BGPTreatAsWithdrawException withdrawCause) throws BGPDocumentedException {
291         final AttributesBuilder builder = new AttributesBuilder();
292         final MpReachNlri mpReachNlri = getMpReach(parsed);
293         if (mpReachNlri == null) {
294             // No MP_REACH attribute, just reuse MP_UNREACH if it is present.
295             builder.addAugmentation(Attributes2.class, parsed.augmentation(Attributes2.class));
296             return builder.build();
297         }
298
299         final MpUnreachNlri unreachNlri = getMpUnreach(parsed);
300         if (unreachNlri != null) {
301             final TablesKey reachKey = new TablesKey(mpReachNlri.getAfi(), mpReachNlri.getSafi());
302             final TablesKey unreachKey = new TablesKey(unreachNlri.getAfi(), unreachNlri.getSafi());
303             if (!reachKey.equals(unreachKey)) {
304                 LOG.warn("Unexpected mismatch between MP_REACH ({}) and MP_UNREACH ({})", reachKey, unreachKey,
305                     withdrawCause);
306                 throw new BGPDocumentedException(withdrawCause);
307             }
308         }
309
310         final MpUnreachNlri converted = this.nlriReg.convertMpReachToMpUnReach(mpReachNlri, unreachNlri)
311                 .orElseThrow(() -> {
312                     LOG.warn("Could not convert attributes {} to withdraw attributes", parsed, withdrawCause);
313                     return new BGPDocumentedException(withdrawCause);
314                 });
315
316         builder.addAugmentation(Attributes2.class, new Attributes2Builder().setMpUnreachNlri(converted).build());
317         return builder.build();
318     }
319
320     private static MpReachNlri getMpReach(final Attributes attrs) {
321         final Attributes1 reachAttr = attrs.augmentation(Attributes1.class);
322         return reachAttr == null ? null : reachAttr.getMpReachNlri();
323     }
324
325     private static MpUnreachNlri getMpUnreach(final Attributes attrs) {
326         final Attributes2 unreachAttr = attrs.augmentation(Attributes2.class);
327         return unreachAttr == null ? null : unreachAttr.getMpUnreachNlri();
328     }
329 }