2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.bgp.parser.impl.message;
10 import io.netty.buffer.ByteBuf;
12 import java.util.Arrays;
13 import java.util.List;
15 import java.util.Map.Entry;
17 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
18 import org.opendaylight.protocol.bgp.parser.BGPError;
19 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
20 import org.opendaylight.protocol.bgp.parser.spi.MessageParser;
21 import org.opendaylight.protocol.bgp.parser.spi.MessageSerializer;
22 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
23 import org.opendaylight.protocol.bgp.parser.spi.ParameterRegistry;
24 import org.opendaylight.protocol.concepts.Ipv4Util;
25 import org.opendaylight.protocol.util.ByteArray;
26 import org.opendaylight.protocol.util.Values;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
32 import org.opendaylight.yangtools.yang.binding.Notification;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
36 import com.google.common.base.Preconditions;
37 import com.google.common.collect.Lists;
38 import com.google.common.collect.Maps;
39 import com.google.common.primitives.UnsignedBytes;
42 * Parser for BGP Open message.
44 public final class BGPOpenMessageParser implements MessageParser, MessageSerializer {
45 public static final int TYPE = 1;
47 private static final Logger LOG = LoggerFactory.getLogger(BGPOpenMessageParser.class);
49 private static final int VERSION_SIZE = 1;
50 private static final int AS_SIZE = 2;
51 private static final int HOLD_TIME_SIZE = 2;
52 private static final int BGP_ID_SIZE = 4;
53 private static final int OPT_PARAM_LENGTH_SIZE = 1;
55 private static final int MIN_MSG_LENGTH = VERSION_SIZE + AS_SIZE + HOLD_TIME_SIZE + BGP_ID_SIZE + OPT_PARAM_LENGTH_SIZE;
57 private static final int BGP_VERSION = 4;
59 private static final int AS_TRANS = 2345;
61 private final ParameterRegistry reg;
63 public BGPOpenMessageParser(final ParameterRegistry reg) {
64 this.reg = Preconditions.checkNotNull(reg);
68 * Serializes given BGP Open message to byte array, without the header.
70 * @param msg BGP Open message to be serialized.
71 * @return BGP Open message converted to byte array
74 public byte[] serializeMessage(final Notification msg) {
76 throw new IllegalArgumentException("BGPOpen message cannot be null");
78 LOG.trace("Started serializing open message: {}", msg);
79 final Open open = (Open) msg;
81 final Map<byte[], Integer> optParams = Maps.newHashMap();
83 int optParamsLength = 0;
85 if (open.getBgpParameters() != null) {
86 for (final BgpParameters param : open.getBgpParameters()) {
87 final byte[] p = this.reg.serializeParameter(param);
89 optParams.put(p, p.length);
90 optParamsLength += p.length;
94 final byte[] msgBody = new byte[MIN_MSG_LENGTH + optParamsLength];
98 msgBody[offset] = UnsignedBytes.checkedCast(BGP_VERSION);
99 offset += VERSION_SIZE;
101 // When our AS number does not fit into two bytes, we report it as AS_TRANS
102 int openAS = open.getMyAsNumber();
103 if (openAS > Values.UNSIGNED_SHORT_MAX_VALUE) {
106 System.arraycopy(ByteArray.longToBytes(openAS, AS_SIZE), 0, msgBody, offset, AS_SIZE);
109 System.arraycopy(ByteArray.intToBytes(open.getHoldTimer(), HOLD_TIME_SIZE), 0, msgBody, offset, HOLD_TIME_SIZE);
110 offset += HOLD_TIME_SIZE;
112 System.arraycopy(Ipv4Util.bytesForAddress(open.getBgpIdentifier()), 0, msgBody, offset, BGP_ID_SIZE);
113 offset += BGP_ID_SIZE;
115 msgBody[offset] = UnsignedBytes.checkedCast(optParamsLength);
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();
124 final byte[] ret = MessageUtil.formatMessage(TYPE, msgBody);
125 LOG.trace("Open message serialized to: {}", Arrays.toString(ret));
130 * Parses given byte array to BGP Open message
132 * @param body byte array representing BGP Open message, without header
133 * @return BGP Open Message
134 * @throws BGPDocumentedException if the parsing was unsuccessful
137 public Open parseMessageBody(final ByteBuf body, final int messageLength) throws BGPDocumentedException {
139 throw new IllegalArgumentException("Byte array cannot be null.");
141 LOG.trace("Started parsing of open message: {}", Arrays.toString(ByteArray.getAllBytes(body)));
143 if (body.readableBytes() < MIN_MSG_LENGTH) {
144 throw BGPDocumentedException.badMessageLength("Open message too small.", messageLength);
146 int version = UnsignedBytes.toInt(body.readByte());
147 if (version != BGP_VERSION) {
148 throw new BGPDocumentedException("BGP Protocol version " + version + " not supported.", BGPError.VERSION_NOT_SUPPORTED);
150 final AsNumber as = new AsNumber((long) body.readUnsignedShort());
151 final int holdTime = body.readUnsignedShort();
152 if (holdTime == 1 || holdTime == 2) {
153 throw new BGPDocumentedException("Hold time value not acceptable.", BGPError.HOLD_TIME_NOT_ACC);
155 Ipv4Address bgpId = null;
157 bgpId = Ipv4Util.addressForBytes(ByteArray.readBytes(body, BGP_ID_SIZE));
158 } catch (final IllegalArgumentException e) {
159 throw new BGPDocumentedException("BGP Identifier is not a valid IPv4 Address", BGPError.BAD_BGP_ID, e);
161 final int optLength = UnsignedBytes.toInt(body.readByte());
163 final List<BgpParameters> optParams = Lists.newArrayList();
165 fillParams(body.slice(body.readerIndex(), optLength), optParams);
167 LOG.trace("Open message was parsed: AS = {}, holdTimer = {}, bgpId = {}, optParams = {}", as, holdTime, bgpId, optParams);
168 return new OpenBuilder().setMyAsNumber(as.getValue().intValue()).setHoldTimer(holdTime).setBgpIdentifier(bgpId).setBgpParameters(
172 private void fillParams(final ByteBuf buffer, final List<BgpParameters> params) throws BGPDocumentedException {
173 Preconditions.checkArgument(buffer != null && buffer.readableBytes() != 0, "Byte array cannot be null or empty.");
174 LOG.trace("Started parsing of BGP parameter: {}", Arrays.toString(ByteArray.getAllBytes(buffer)));
175 while (buffer.readableBytes() != 0) {
176 if (buffer.readableBytes() <= 2) {
177 throw new BGPDocumentedException("Malformed parameter encountered (" + buffer.readableBytes() + " bytes left)", BGPError.OPT_PARAM_NOT_SUPPORTED);
179 final int paramType = UnsignedBytes.toInt(buffer.readByte());
180 final int paramLength = UnsignedBytes.toInt(buffer.readByte());
181 final ByteBuf paramBody = buffer.slice(buffer.readerIndex(), paramLength);
183 final BgpParameters param;
185 param = this.reg.parseParameter(paramType, paramBody);
186 } catch (final BGPParsingException e) {
187 throw new BGPDocumentedException("Optional parameter not parsed", BGPError.UNSPECIFIC_OPEN_ERROR, e);
192 LOG.debug("Ignoring BGP Parameter type: {}", paramType);
194 buffer.skipBytes(paramLength);
196 LOG.trace("Parsed BGP parameters: {}", Arrays.toString(params.toArray()));