Bug-731: Fixed few major Sonar warnings
[bgpcep.git] / bgp / parser-impl / src / main / java / org / opendaylight / protocol / bgp / parser / impl / message / BGPUpdateMessageParser.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
11 import com.google.common.base.Preconditions;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.buffer.ByteBufUtil;
14 import io.netty.buffer.Unpooled;
15 import java.util.List;
16 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
17 import org.opendaylight.protocol.bgp.parser.BGPError;
18 import org.opendaylight.protocol.bgp.parser.BGPParsingException;
19 import org.opendaylight.protocol.bgp.parser.spi.AttributeRegistry;
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.util.ByteArray;
24 import org.opendaylight.protocol.util.Ipv4Util;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.UpdateBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.Nlri;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.NlriBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributes;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.WithdrawnRoutes;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.WithdrawnRoutesBuilder;
33 import org.opendaylight.yangtools.yang.binding.Notification;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * LENGTH fields, that denote the length of the fields with variable length, have fixed SIZE.
39  *
40  * @see <a href="http://tools.ietf.org/html/rfc4271#section-4.3">BGP-4 Update Message Format</a>
41  */
42 public class BGPUpdateMessageParser implements MessageParser, MessageSerializer {
43     public static final int TYPE = 2;
44
45     private static final Logger LOG = LoggerFactory.getLogger(BGPUpdateMessageParser.class);
46
47     /**
48      * Size of the withdrawn_routes_length field, in bytes.
49      */
50     public static final int WITHDRAWN_ROUTES_LENGTH_SIZE = 2;
51     /**
52      * Size of the total_path_attr_length field, in bytes.
53      */
54     public static final int TOTAL_PATH_ATTR_LENGTH_SIZE = 2;
55
56     private final AttributeRegistry reg;
57
58     // Constructors -------------------------------------------------------
59     public BGPUpdateMessageParser(final AttributeRegistry reg) {
60         this.reg = Preconditions.checkNotNull(reg);
61     }
62
63     // Getters & setters --------------------------------------------------
64
65     @Override
66     public Update parseMessageBody(final ByteBuf buffer, final int messageLength) throws BGPDocumentedException {
67         Preconditions.checkArgument(buffer != null && buffer.readableBytes() != 0, "Byte array cannot be null or empty.");
68         LOG.trace("Started parsing of update message: {}", ByteBufUtil.hexDump(buffer));
69
70         final int withdrawnRoutesLength = buffer.readUnsignedShort();
71         final UpdateBuilder eventBuilder = new UpdateBuilder();
72
73         if (withdrawnRoutesLength > 0) {
74             final List<Ipv4Prefix> withdrawnRoutes = Ipv4Util.prefixListForBytes(ByteArray.readBytes(buffer, withdrawnRoutesLength));
75             eventBuilder.setWithdrawnRoutes(new WithdrawnRoutesBuilder().setWithdrawnRoutes(withdrawnRoutes).build());
76         }
77         final int totalPathAttrLength = buffer.readUnsignedShort();
78
79         if (withdrawnRoutesLength == 0 && totalPathAttrLength == 0) {
80             return eventBuilder.build();
81         }
82         if (totalPathAttrLength > 0) {
83             try {
84                 final PathAttributes pathAttributes = this.reg.parseAttributes(buffer.slice(buffer.readerIndex(), totalPathAttrLength));
85                 buffer.skipBytes(totalPathAttrLength);
86                 eventBuilder.setPathAttributes(pathAttributes);
87             } catch (final BGPParsingException | RuntimeException e) {
88                 // Catch everything else and turn it into a BGPDocumentedException
89                 LOG.warn("Could not parse BGP attributes", e);
90                 throw new BGPDocumentedException("Could not parse BGP attributes.", BGPError.MALFORMED_ATTR_LIST, e);
91             }
92         }
93         final List<Ipv4Prefix> nlri = Ipv4Util.prefixListForBytes(ByteArray.readAllBytes(buffer));
94         if (nlri != null && !nlri.isEmpty()) {
95             eventBuilder.setNlri(new NlriBuilder().setNlri(nlri).build());
96         }
97         final Update msg = eventBuilder.build();
98         LOG.debug("BGP Update message was parsed {}.", msg);
99         return msg;
100     }
101
102     @Override
103     public void serializeMessage(final Notification message, final ByteBuf bytes) {
104         Preconditions.checkArgument(message instanceof Update, "BGPUpdate message cannot be null");
105         LOG.trace("Started serializing update message: {}", message);
106         final Update update = (Update) message;
107
108         final ByteBuf messageBody = Unpooled.buffer();
109         final WithdrawnRoutes withdrawnRoutes = update.getWithdrawnRoutes();
110         if (withdrawnRoutes != null) {
111             final ByteBuf withdrawnRoutesBuf = Unpooled.buffer();
112             for (final Ipv4Prefix prefix : withdrawnRoutes.getWithdrawnRoutes()) {
113                 withdrawnRoutesBuf.writeBytes(Ipv4Util.bytesForPrefixBegin(prefix));
114             }
115             messageBody.writeShort(withdrawnRoutesBuf.writerIndex());
116             messageBody.writeBytes(withdrawnRoutesBuf);
117         } else {
118             messageBody.writeZero(WITHDRAWN_ROUTES_LENGTH_SIZE);
119         }
120         if (update.getPathAttributes() != null) {
121             final ByteBuf pathAttributesBuf = Unpooled.buffer();
122             this.reg.serializeAttribute(update.getPathAttributes(), pathAttributesBuf);
123             messageBody.writeShort(pathAttributesBuf.writerIndex());
124             messageBody.writeBytes(pathAttributesBuf);
125         } else {
126             messageBody.writeZero(TOTAL_PATH_ATTR_LENGTH_SIZE);
127         }
128         final Nlri nlri = update.getNlri();
129         if (nlri != null) {
130             for (final Ipv4Prefix prefix : nlri.getNlri()) {
131                 messageBody.writeBytes(Ipv4Util.bytesForPrefixBegin(prefix));
132             }
133         }
134         LOG.trace("Update message serialized to {}", ByteBufUtil.hexDump(messageBody));
135         MessageUtil.formatMessage(TYPE, messageBody, bytes);
136     }
137 }