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