Improved logging in BGP.
[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 io.netty.buffer.ByteBuf;
11
12 import java.util.Arrays;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Map.Entry;
16
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;
35
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;
40
41 /**
42  * Parser for BGP Open message.
43  */
44 public final class BGPOpenMessageParser implements MessageParser, MessageSerializer {
45         public static final int TYPE = 1;
46
47         private static final Logger LOG = LoggerFactory.getLogger(BGPOpenMessageParser.class);
48
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;
54
55         private static final int MIN_MSG_LENGTH = VERSION_SIZE + AS_SIZE + HOLD_TIME_SIZE + BGP_ID_SIZE + OPT_PARAM_LENGTH_SIZE;
56
57         private static final int BGP_VERSION = 4;
58
59         private static final int AS_TRANS = 2345;
60
61         private final ParameterRegistry reg;
62
63         public BGPOpenMessageParser(final ParameterRegistry reg) {
64                 this.reg = Preconditions.checkNotNull(reg);
65         }
66
67         /**
68          * Serializes given BGP Open message to byte array, without the header.
69          * 
70          * @param msg BGP Open message to be serialized.
71          * @return BGP Open message converted to byte array
72          */
73         @Override
74         public byte[] serializeMessage(final Notification msg) {
75                 if (msg == null) {
76                         throw new IllegalArgumentException("BGPOpen message cannot be null");
77                 }
78                 LOG.trace("Started serializing open message: {}", msg);
79                 final Open open = (Open) msg;
80
81                 final Map<byte[], Integer> optParams = Maps.newHashMap();
82
83                 int optParamsLength = 0;
84
85                 if (open.getBgpParameters() != null) {
86                         for (final BgpParameters param : open.getBgpParameters()) {
87                                 final byte[] p = this.reg.serializeParameter(param);
88                                 if (p != null) {
89                                         optParams.put(p, p.length);
90                                         optParamsLength += p.length;
91                                 }
92                         }
93                 }
94                 final byte[] msgBody = new byte[MIN_MSG_LENGTH + optParamsLength];
95
96                 int offset = 0;
97
98                 msgBody[offset] = UnsignedBytes.checkedCast(BGP_VERSION);
99                 offset += VERSION_SIZE;
100
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) {
104                         openAS = AS_TRANS;
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                 final byte[] ret = MessageUtil.formatMessage(TYPE, msgBody);
125                 LOG.trace("Open message serialized to: {}", Arrays.toString(ret));
126                 return ret;
127         }
128
129         /**
130          * Parses given byte array to BGP Open message
131          * 
132          * @param body byte array representing BGP Open message, without header
133          * @return BGP Open Message
134          * @throws BGPDocumentedException if the parsing was unsuccessful
135          */
136         @Override
137         public Open parseMessageBody(final ByteBuf body, final int messageLength) throws BGPDocumentedException {
138                 if (body == null) {
139                         throw new IllegalArgumentException("Byte array cannot be null.");
140                 }
141                 LOG.trace("Started parsing of open message: {}", Arrays.toString(ByteArray.getAllBytes(body)));
142
143                 if (body.readableBytes() < MIN_MSG_LENGTH) {
144                         throw BGPDocumentedException.badMessageLength("Open message too small.", messageLength);
145                 }
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);
149                 }
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);
154                 }
155                 Ipv4Address bgpId = null;
156                 try {
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);
160                 }
161                 final int optLength = UnsignedBytes.toInt(body.readByte());
162
163                 final List<BgpParameters> optParams = Lists.newArrayList();
164                 if (optLength > 0) {
165                         fillParams(body.slice(body.readerIndex(), optLength), optParams);
166                 }
167                 LOG.debug("BGP 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(
169                                 optParams).build();
170         }
171
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);
178                         }
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);
182
183                         final BgpParameters param;
184                         try {
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);
188                         }
189                         if (param != null) {
190                                 params.add(param);
191                         } else {
192                                 LOG.debug("Ignoring BGP Parameter type: {}", paramType);
193                         }
194                         buffer.skipBytes(paramLength);
195                 }
196                 LOG.trace("Parsed BGP parameters: {}", Arrays.toString(params.toArray()));
197         }
198 }