Fix most bgp-parser-impl checkstyle
[bgpcep.git] / bgp / parser-impl / src / main / java / org / opendaylight / protocol / bgp / parser / impl / message / BGPOpenMessageParser.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 io.netty.buffer.ByteBuf;
14 import io.netty.buffer.ByteBufUtil;
15 import io.netty.buffer.Unpooled;
16 import java.util.ArrayList;
17 import java.util.List;
18 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
19 import org.opendaylight.protocol.bgp.parser.BGPError;
20 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
21 import org.opendaylight.protocol.bgp.parser.spi.MessageParser;
22 import org.opendaylight.protocol.bgp.parser.spi.MessageSerializer;
23 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
24 import org.opendaylight.protocol.bgp.parser.spi.ParameterRegistry;
25 import org.opendaylight.protocol.bgp.parser.spi.PeerSpecificParserConstraint;
26 import org.opendaylight.protocol.util.Ipv4Util;
27 import org.opendaylight.protocol.util.Values;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.OpenBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.BgpParameters;
33 import org.opendaylight.yangtools.yang.binding.Notification;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * Parser for BGP Open message.
39  */
40 public final class BGPOpenMessageParser implements MessageParser, MessageSerializer {
41
42     private static final Logger LOG = LoggerFactory.getLogger(BGPOpenMessageParser.class);
43
44     public static final int TYPE = 1;
45
46     private static final int VERSION_SIZE = 1;
47     private static final int AS_SIZE = 2;
48     private static final int HOLD_TIME_SIZE = 2;
49     private static final int BGP_ID_SIZE = 4;
50     private static final int OPT_PARAM_LENGTH_SIZE = 1;
51
52     private static final int MIN_MSG_LENGTH = VERSION_SIZE + AS_SIZE
53             + HOLD_TIME_SIZE + BGP_ID_SIZE + OPT_PARAM_LENGTH_SIZE;
54
55     private static final int BGP_VERSION = 4;
56
57     public static final int AS_TRANS = 23456;
58
59     private final ParameterRegistry reg;
60
61     public BGPOpenMessageParser(final ParameterRegistry reg) {
62         this.reg = requireNonNull(reg);
63     }
64
65     /**
66      * Serializes given BGP Open message to byte array, without the header.
67      *
68      * @param msg BGP Open message to be serialized.
69      * @param bytes ByteBuf where the message will be serialized
70      */
71     @Override
72     public void serializeMessage(final Notification msg, final ByteBuf bytes) {
73         Preconditions.checkArgument(msg instanceof Open, "Message needs to be of type Open");
74         final Open open = (Open) msg;
75         final ByteBuf msgBody = Unpooled.buffer();
76
77         msgBody.writeByte(BGP_VERSION);
78
79         // When our AS number does not fit into two bytes, we report it as AS_TRANS
80         int openAS = open.getMyAsNumber();
81         if (openAS > Values.UNSIGNED_SHORT_MAX_VALUE) {
82             openAS = AS_TRANS;
83         }
84         msgBody.writeShort(openAS);
85         msgBody.writeShort(open.getHoldTimer());
86         msgBody.writeBytes(Ipv4Util.bytesForAddress(open.getBgpIdentifier()));
87
88         final ByteBuf paramsBuffer = Unpooled.buffer();
89         if (open.getBgpParameters() != null) {
90             for (final BgpParameters param : open.getBgpParameters()) {
91                 this.reg.serializeParameter(param, paramsBuffer);
92             }
93         }
94         msgBody.writeByte(paramsBuffer.writerIndex());
95         msgBody.writeBytes(paramsBuffer);
96
97         MessageUtil.formatMessage(TYPE, msgBody, bytes);
98     }
99
100     /**
101      * Parses given byte array to BGP Open message.
102      *
103      * @param body byte array representing BGP Open message, without header
104      * @param messageLength the length of the message
105      * @return {@link Open} BGP Open Message
106      * @throws BGPDocumentedException if the parsing was unsuccessful
107      */
108     @Override
109     public Open parseMessageBody(final ByteBuf body, final int messageLength,
110             final PeerSpecificParserConstraint constraint) throws BGPDocumentedException {
111         Preconditions.checkArgument(body != null, "Buffer cannot be null.");
112
113         if (body.readableBytes() < MIN_MSG_LENGTH) {
114             throw BGPDocumentedException.badMessageLength("Open message too small.", messageLength);
115         }
116         final int version = body.readUnsignedByte();
117         if (version != BGP_VERSION) {
118             throw new BGPDocumentedException("BGP Protocol version " + version + " not supported.",
119                     BGPError.VERSION_NOT_SUPPORTED);
120         }
121         final AsNumber as = new AsNumber((long) body.readUnsignedShort());
122         final int holdTime = body.readUnsignedShort();
123         if (holdTime == 1 || holdTime == 2) {
124             throw new BGPDocumentedException("Hold time value not acceptable.", BGPError.HOLD_TIME_NOT_ACC);
125         }
126         Ipv4Address bgpId;
127         try {
128             bgpId = Ipv4Util.addressForByteBuf(body);
129         } catch (final IllegalArgumentException e) {
130             throw new BGPDocumentedException("BGP Identifier is not a valid IPv4 Address", BGPError.BAD_BGP_ID, e);
131         }
132         final int optLength = body.readUnsignedByte();
133
134         final List<BgpParameters> optParams = new ArrayList<>();
135         if (optLength > 0) {
136             fillParams(body.slice(), optParams);
137         }
138         LOG.debug("BGP Open message was parsed: AS = {}, holdTimer = {}, bgpId = {}, optParams = {}", as,
139                 holdTime, bgpId, optParams);
140         return new OpenBuilder().setMyAsNumber(as.getValue().intValue()).setHoldTimer(holdTime)
141                 .setBgpIdentifier(bgpId).setBgpParameters(optParams).build();
142     }
143
144     private void fillParams(final ByteBuf buffer, final List<BgpParameters> params) throws BGPDocumentedException {
145         Preconditions.checkArgument(buffer != null && buffer.isReadable(),
146                 "Buffer cannot be null or empty.");
147         if (LOG.isTraceEnabled()) {
148             LOG.trace("Started parsing of BGP parameter: {}", ByteBufUtil.hexDump(buffer));
149         }
150         while (buffer.isReadable()) {
151             if (buffer.readableBytes() <= 2) {
152                 throw new BGPDocumentedException("Malformed parameter encountered (" + buffer.readableBytes()
153                         + " bytes left)", BGPError.OPT_PARAM_NOT_SUPPORTED);
154             }
155             final int paramType = buffer.readUnsignedByte();
156             final int paramLength = buffer.readUnsignedByte();
157             final ByteBuf paramBody = buffer.readSlice(paramLength);
158
159             final BgpParameters param;
160             try {
161                 param = this.reg.parseParameter(paramType, paramBody);
162             } catch (final BGPParsingException e) {
163                 throw new BGPDocumentedException("Optional parameter not parsed", BGPError.UNSPECIFIC_OPEN_ERROR, e);
164             }
165             if (param != null) {
166                 params.add(param);
167             } else {
168                 LOG.debug("Ignoring BGP Parameter type: {}", paramType);
169             }
170         }
171         LOG.trace("Parsed BGP parameters: {}", params);
172     }
173 }