Merge "Add EPL license declaration"
[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 java.util.Arrays;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Map.Entry;
14
15 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
16 import org.opendaylight.protocol.bgp.parser.BGPError;
17 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
18 import org.opendaylight.protocol.bgp.parser.spi.MessageParser;
19 import org.opendaylight.protocol.bgp.parser.spi.MessageSerializer;
20 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
21 import org.opendaylight.protocol.bgp.parser.spi.ParameterRegistry;
22 import org.opendaylight.protocol.concepts.Ipv4Util;
23 import org.opendaylight.protocol.util.ByteArray;
24 import org.opendaylight.protocol.util.Values;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
30 import org.opendaylight.yangtools.yang.binding.Notification;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import com.google.common.base.Preconditions;
35 import com.google.common.collect.Lists;
36 import com.google.common.collect.Maps;
37 import com.google.common.primitives.UnsignedBytes;
38
39 /**
40  * Parser for BGP Open message.
41  */
42 public final class BGPOpenMessageParser implements MessageParser, MessageSerializer {
43         public static final int TYPE = 1;
44
45         private static final Logger logger = LoggerFactory.getLogger(BGPOpenMessageParser.class);
46
47         private static final int VERSION_SIZE = 1;
48         private static final int AS_SIZE = 2;
49         private static final int HOLD_TIME_SIZE = 2;
50         private static final int BGP_ID_SIZE = 4;
51         private static final int OPT_PARAM_LENGTH_SIZE = 1;
52
53         private static final int MIN_MSG_LENGTH = VERSION_SIZE + AS_SIZE + HOLD_TIME_SIZE + BGP_ID_SIZE + OPT_PARAM_LENGTH_SIZE;
54
55         private static final int BGP_VERSION = 4;
56
57         private static final int AS_TRANS = 2345;
58
59         private final ParameterRegistry reg;
60
61         public BGPOpenMessageParser(final ParameterRegistry reg) {
62                 this.reg = Preconditions.checkNotNull(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          * @return BGP Open message converted to byte array
70          */
71         @Override
72         public byte[] serializeMessage(final Notification msg) {
73                 if (msg == null) {
74                         throw new IllegalArgumentException("BGPOpen message cannot be null");
75                 }
76                 logger.trace("Started serializing open message: {}", msg);
77                 final Open open = (Open) msg;
78
79                 final Map<byte[], Integer> optParams = Maps.newHashMap();
80
81                 int optParamsLength = 0;
82
83                 if (open.getBgpParameters() != null) {
84                         for (final BgpParameters param : open.getBgpParameters()) {
85                                 final byte[] p = this.reg.serializeParameter(param);
86                                 if (p != null) {
87                                         optParams.put(p, p.length);
88                                         optParamsLength += p.length;
89                                 }
90                         }
91                 }
92
93                 final byte[] msgBody = new byte[MIN_MSG_LENGTH + optParamsLength];
94
95                 int offset = 0;
96
97                 msgBody[offset] = UnsignedBytes.checkedCast(BGP_VERSION);
98                 offset += VERSION_SIZE;
99
100                 // When our AS number does not fit into two bytes, we report it as AS_TRANS
101                 int openAS = open.getMyAsNumber();
102                 if (openAS > Values.UNSIGNED_SHORT_MAX_VALUE) {
103                         openAS = AS_TRANS;
104                 }
105
106                 System.arraycopy(ByteArray.longToBytes(openAS, AS_SIZE), 0, msgBody, offset, AS_SIZE);
107                 offset += AS_SIZE;
108
109                 System.arraycopy(ByteArray.intToBytes(open.getHoldTimer(), HOLD_TIME_SIZE), 0, msgBody, offset, HOLD_TIME_SIZE);
110                 offset += HOLD_TIME_SIZE;
111
112                 System.arraycopy(Ipv4Util.bytesForAddress(open.getBgpIdentifier()), 0, msgBody, offset, BGP_ID_SIZE);
113                 offset += BGP_ID_SIZE;
114
115                 msgBody[offset] = UnsignedBytes.checkedCast(optParamsLength);
116
117                 int index = MIN_MSG_LENGTH;
118                 if (optParams != null) {
119                         for (final Entry<byte[], Integer> entry : optParams.entrySet()) {
120                                 System.arraycopy(entry.getKey(), 0, msgBody, index, entry.getValue());
121                                 index += entry.getValue();
122                         }
123                 }
124
125                 final byte[] ret = MessageUtil.formatMessage(TYPE, msgBody);
126                 logger.trace("Open message serialized to: {}", Arrays.toString(ret));
127                 return ret;
128         }
129
130         /**
131          * Parses given byte array to BGP Open message
132          * 
133          * @param body byte array representing BGP Open message, without header
134          * @return BGP Open Message
135          * @throws BGPDocumentedException if the parsing was unsuccessful
136          */
137         @Override
138         public Open parseMessageBody(final byte[] body, final int messageLength) throws BGPDocumentedException {
139                 if (body == null) {
140                         throw new IllegalArgumentException("Byte array cannot be null.");
141                 }
142                 logger.trace("Started parsing of open message: {}", Arrays.toString(body));
143
144                 if (body.length < MIN_MSG_LENGTH) {
145                         throw BGPDocumentedException.badMessageLength("Open message too small.", messageLength);
146                 }
147                 if (UnsignedBytes.toInt(body[0]) != BGP_VERSION) {
148                         throw new BGPDocumentedException("BGP Protocol version " + UnsignedBytes.toInt(body[0]) + " not supported.", BGPError.VERSION_NOT_SUPPORTED);
149                 }
150
151                 int offset = VERSION_SIZE;
152                 final AsNumber as = new AsNumber(ByteArray.bytesToLong(ByteArray.subByte(body, offset, AS_SIZE)));
153                 offset += AS_SIZE;
154
155                 // TODO: BAD_PEER_AS Error: when is an AS unacceptable?
156
157                 final short holdTime = ByteArray.bytesToShort(ByteArray.subByte(body, offset, HOLD_TIME_SIZE));
158                 offset += HOLD_TIME_SIZE;
159                 if (holdTime == 1 || holdTime == 2) {
160                         throw new BGPDocumentedException("Hold time value not acceptable.", BGPError.HOLD_TIME_NOT_ACC);
161                 }
162
163                 Ipv4Address bgpId = null;
164                 try {
165                         bgpId = Ipv4Util.addressForBytes(ByteArray.subByte(body, offset, BGP_ID_SIZE));
166                 } catch (final IllegalArgumentException e) {
167                         throw new BGPDocumentedException("BGP Identifier is not a valid IPv4 Address", BGPError.BAD_BGP_ID, e);
168                 }
169                 offset += BGP_ID_SIZE;
170
171                 final int optLength = UnsignedBytes.toInt(body[offset]);
172
173                 final List<BgpParameters> optParams = Lists.newArrayList();
174                 if (optLength > 0) {
175                         fillParams(ByteArray.subByte(body, MIN_MSG_LENGTH, optLength), optParams);
176                 }
177                 logger.trace("Open message was parsed: AS = {}, holdTimer = {}, bgpId = {}, optParams = {}", as, holdTime, bgpId, optParams);
178                 return new OpenBuilder().setMyAsNumber(as.getValue().intValue()).setHoldTimer((int) holdTime).setBgpIdentifier(bgpId).setBgpParameters(
179                                 optParams).build();
180         }
181
182         private void fillParams(final byte[] bytes, final List<BgpParameters> params) throws BGPDocumentedException {
183                 if (bytes == null || bytes.length == 0) {
184                         throw new IllegalArgumentException("Byte array cannot be null or empty.");
185                 }
186
187                 logger.trace("Started parsing of BGP parameter: {}", Arrays.toString(bytes));
188                 int byteOffset = 0;
189                 while (byteOffset < bytes.length) {
190                         if (byteOffset + 2 >= bytes.length) {
191                                 // FIXME: throw a BGPDocumentedException here?
192                                 throw new IllegalArgumentException("Malformed parameter encountered (" + (bytes.length - byteOffset) + " bytes left)");
193                         }
194
195                         final int paramType = UnsignedBytes.toInt(bytes[byteOffset++]);
196                         final int paramLength = UnsignedBytes.toInt(bytes[byteOffset++]);
197                         final byte[] paramBody = ByteArray.subByte(bytes, byteOffset, paramLength);
198                         byteOffset += paramLength;
199
200                         final BgpParameters param;
201                         try {
202                                 param = this.reg.parseParameter(paramType, paramBody);
203                         } catch (final BGPParsingException e) {
204                                 throw new BGPDocumentedException("Optional parameter not parsed", BGPError.UNSPECIFIC_OPEN_ERROR, e);
205                         }
206
207                         if (param != null) {
208                                 params.add(param);
209                         } else {
210                                 logger.debug("Ignoring BGP Parameter type: {}", paramType);
211                         }
212                 }
213
214                 logger.trace("Parsed BGP parameters: {}", Arrays.toString(params.toArray()));
215         }
216 }