21dc7c8a978e664fe1fdadcad0a714dda932207f
[bgpcep.git] / bgp / parser-impl / src / main / java / org / opendaylight / protocol / bgp / parser / impl / BGPMessageFactoryImpl.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;
9
10 import java.util.Arrays;
11 import java.util.List;
12
13 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
14 import org.opendaylight.protocol.bgp.parser.BGPError;
15 import org.opendaylight.protocol.bgp.parser.BGPMessage;
16 import org.opendaylight.protocol.bgp.parser.BGPMessageFactory;
17 import org.opendaylight.protocol.bgp.parser.impl.message.BGPNotificationMessageParser;
18 import org.opendaylight.protocol.bgp.parser.impl.message.BGPOpenMessageParser;
19 import org.opendaylight.protocol.bgp.parser.impl.message.BGPUpdateMessageParser;
20 import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
21 import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
22 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
23 import org.opendaylight.protocol.framework.DeserializerException;
24 import org.opendaylight.protocol.framework.DocumentedException;
25 import org.opendaylight.protocol.util.ByteArray;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import com.google.common.collect.Lists;
30 import com.google.common.primitives.UnsignedBytes;
31
32 /**
33  * The byte array
34  */
35 public final class BGPMessageFactoryImpl implements BGPMessageFactory {
36
37         private final static Logger logger = LoggerFactory.getLogger(BGPMessageFactoryImpl.class);
38
39         final static int LENGTH_FIELD_LENGTH = 2; // bytes
40
41         private final static int TYPE_FIELD_LENGTH = 1; // bytes
42
43         final static int MARKER_LENGTH = 16; // bytes
44
45         public final static int COMMON_HEADER_LENGTH = LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH + MARKER_LENGTH;
46
47         /*
48          * (non-Javadoc)
49          * @see org.opendaylight.protocol.bgp.parser.BGPMessageParser#parse(byte[])
50          */
51         @Override
52         public List<BGPMessage> parse(final byte[] bytes) throws DeserializerException, DocumentedException {
53                 if (bytes == null) {
54                         throw new IllegalArgumentException("Array of bytes is mandatory.");
55                 }
56                 if (bytes.length < COMMON_HEADER_LENGTH) {
57                         throw new IllegalArgumentException("Too few bytes in passed array. Passed: " + bytes.length + ". Expected: >= "
58                                         + COMMON_HEADER_LENGTH + ".");
59                 }
60                 /*
61                  * byte array starts with message length
62                  */
63                 // final byte[] ones = new byte[MARKER_LENGTH];
64                 // Arrays.fill(ones, (byte)0xff);
65                 // if (Arrays.equals(bytes, ones))
66                 // throw new BGPDocumentedException("Marker not set to ones.", BGPError.CONNECTION_NOT_SYNC);
67                 final byte[] bs = ByteArray.cutBytes(bytes, MARKER_LENGTH);
68                 final int messageLength = ByteArray.bytesToInt(ByteArray.subByte(bs, 0, LENGTH_FIELD_LENGTH));
69                 final int messageType = UnsignedBytes.toInt(bs[LENGTH_FIELD_LENGTH]);
70
71                 final byte[] msgBody = ByteArray.cutBytes(bs, LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH);
72
73                 if (messageLength < COMMON_HEADER_LENGTH) {
74                         throw new BGPDocumentedException("Message length field not within valid range.", BGPError.BAD_MSG_LENGTH, ByteArray.subByte(bs,
75                                         0, LENGTH_FIELD_LENGTH));
76                 }
77                 if (msgBody.length != messageLength - COMMON_HEADER_LENGTH) {
78                         throw new DeserializerException("Size doesn't match size specified in header. Passed: " + msgBody.length + "; Expected: "
79                                         + (messageLength - COMMON_HEADER_LENGTH) + ". ");
80                 }
81
82                 logger.debug("Attempt to parse message from bytes: {}", ByteArray.bytesToHexString(msgBody));
83
84                 final BGPMessage msg;
85
86                 switch (messageType) {
87                 case 1:
88                         msg = BGPOpenMessageParser.parse(msgBody);
89                         logger.debug("Received and parsed Open Message: {}", msg);
90                         break;
91                 case 2:
92                         msg = BGPUpdateMessageParser.parse(msgBody, messageLength);
93                         logger.debug("Received and parsed Update Message: {}", msg);
94                         break;
95                 case 3:
96                         msg = BGPNotificationMessageParser.parse(msgBody);
97                         logger.debug("Received and parsed Notification Message: {}", msg);
98                         break;
99                 case 4:
100                         msg = new BGPKeepAliveMessage();
101                         if (messageLength != COMMON_HEADER_LENGTH) {
102                                 throw new BGPDocumentedException("Message length field not within valid range.", BGPError.BAD_MSG_LENGTH, ByteArray.subByte(
103                                                 bs, 0, LENGTH_FIELD_LENGTH));
104                         }
105                         break;
106                 default:
107                         throw new BGPDocumentedException("Unhandled message type " + messageType, BGPError.BAD_MSG_TYPE, new byte[] { bs[LENGTH_FIELD_LENGTH] });
108                 }
109
110                 return Lists.newArrayList(msg);
111         }
112
113         @Override
114         public byte[] put(final BGPMessage msg) {
115                 if (msg == null) {
116                         throw new IllegalArgumentException("BGPMessage is mandatory.");
117                 }
118
119                 logger.trace("Serializing {}", msg);
120
121                 byte[] msgBody = null;
122                 int msgType = 0;
123
124                 /*
125                  * Update message is not supported
126                  */
127                 if (msg instanceof BGPOpenMessage) {
128                         msgType = 1;
129                         msgBody = BGPOpenMessageParser.put((BGPOpenMessage) msg);
130                 } else if (msg instanceof BGPNotificationMessage) {
131                         msgType = 3;
132                         msgBody = BGPNotificationMessageParser.put((BGPNotificationMessage) msg);
133                 } else if (msg instanceof BGPKeepAliveMessage) {
134                         msgType = 4;
135                         msgBody = new byte[0];
136                 } else {
137                         throw new IllegalArgumentException("Unknown instance of BGPMessage. Passed " + msg.getClass());
138                 }
139
140                 final byte[] headerBytes = headerToBytes(msgBody.length + COMMON_HEADER_LENGTH, msgType);
141                 final byte[] retBytes = new byte[headerBytes.length + msgBody.length];
142
143                 ByteArray.copyWhole(headerBytes, retBytes, 0);
144                 ByteArray.copyWhole(msgBody, retBytes, COMMON_HEADER_LENGTH);
145
146                 logger.trace("Serialized BGP message {}.", Arrays.toString(retBytes));
147                 return retBytes;
148         }
149
150         /**
151          * Serializes this BGP Message header to byte array.
152          * 
153          * @return byte array representation of this header
154          */
155         public byte[] headerToBytes(final int msgLength, final int msgType) {
156                 final byte[] retBytes = new byte[COMMON_HEADER_LENGTH];
157
158                 Arrays.fill(retBytes, 0, MARKER_LENGTH, (byte) 0xff);
159
160                 System.arraycopy(ByteArray.intToBytes(msgLength), Integer.SIZE / Byte.SIZE - LENGTH_FIELD_LENGTH, retBytes, MARKER_LENGTH,
161                                 LENGTH_FIELD_LENGTH);
162
163                 retBytes[MARKER_LENGTH + LENGTH_FIELD_LENGTH] = (byte) msgType;
164
165                 return retBytes;
166         }
167 }