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