blob: 3a605f4bf3af595567c4b4bec3408159e45f03b4 [file] [log] [blame]
Satish Ke107e662015-09-21 19:00:17 +05301/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.bgp.controller.impl;
18
Shashikanth VH6de20d32015-10-09 12:04:13 +053019import java.io.IOException;
Vidyashree Ramaee293252015-11-18 17:00:11 +053020import java.net.InetAddress;
Shashikanth VH6de20d32015-10-09 12:04:13 +053021import java.net.InetSocketAddress;
22import java.net.SocketAddress;
Vidyashree Ramaee293252015-11-18 17:00:11 +053023import java.net.UnknownHostException;
Shashikanth VH6de20d32015-10-09 12:04:13 +053024import java.nio.channels.ClosedChannelException;
Shashikanth VH9f8afb42015-11-04 18:00:30 +053025import java.util.Collections;
Vidyashree Ramaee293252015-11-18 17:00:11 +053026import java.util.LinkedList;
Shashikanth VH447c6b02015-11-25 21:25:35 +053027import java.util.List;
Vidyashree Ramaee293252015-11-18 17:00:11 +053028import java.util.ListIterator;
Shashikanth VH6de20d32015-10-09 12:04:13 +053029import java.util.concurrent.RejectedExecutionException;
30
Vidyashree Ramaee293252015-11-18 17:00:11 +053031import org.jboss.netty.buffer.ChannelBuffer;
32import org.jboss.netty.buffer.ChannelBuffers;
Shashikanth VH6de20d32015-10-09 12:04:13 +053033import org.jboss.netty.channel.Channel;
34import org.jboss.netty.channel.ChannelHandlerContext;
35import org.jboss.netty.channel.ChannelStateEvent;
36import org.jboss.netty.channel.ExceptionEvent;
37import org.jboss.netty.channel.MessageEvent;
Satish Ke107e662015-09-21 19:00:17 +053038import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
Shashikanth VH6de20d32015-10-09 12:04:13 +053039import org.jboss.netty.handler.timeout.ReadTimeoutException;
40import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
Shashikanth VH9f8afb42015-11-04 18:00:30 +053041import org.onlab.packet.Ip4Address;
Shashikanth VH6de20d32015-10-09 12:04:13 +053042import org.onlab.packet.IpAddress;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053043import org.onosproject.bgp.controller.BgpCfg;
44import org.onosproject.bgp.controller.BgpController;
45import org.onosproject.bgp.controller.BgpId;
46import org.onosproject.bgp.controller.BgpPeer;
47import org.onosproject.bgp.controller.BgpPeerCfg;
48import org.onosproject.bgp.controller.impl.BgpControllerImpl.BgpPeerManagerImpl;
49import org.onosproject.bgpio.exceptions.BgpParseException;
50import org.onosproject.bgpio.protocol.BgpFactory;
51import org.onosproject.bgpio.protocol.BgpMessage;
52import org.onosproject.bgpio.protocol.BgpOpenMsg;
53import org.onosproject.bgpio.protocol.BgpType;
54import org.onosproject.bgpio.protocol.BgpVersion;
55import org.onosproject.bgpio.types.BgpErrorType;
56import org.onosproject.bgpio.types.BgpValueType;
Vidyashree Ramaee293252015-11-18 17:00:11 +053057import org.onosproject.bgpio.types.FourOctetAsNumCapabilityTlv;
58import org.onosproject.bgpio.types.MultiProtocolExtnCapabilityTlv;
Shashikanth VH6de20d32015-10-09 12:04:13 +053059import org.slf4j.Logger;
60import org.slf4j.LoggerFactory;
Satish Ke107e662015-09-21 19:00:17 +053061
62/**
63 * Channel handler deals with the bgp peer connection and dispatches messages from peer to the appropriate locations.
64 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053065class BgpChannelHandler extends IdleStateAwareChannelHandler {
Satish Ke107e662015-09-21 19:00:17 +053066
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053067 private static final Logger log = LoggerFactory.getLogger(BgpChannelHandler.class);
Vidyashree Ramaee293252015-11-18 17:00:11 +053068 static final int BGP_MIN_HOLDTIME = 3;
Shashikanth VH6de20d32015-10-09 12:04:13 +053069 static final int BGP_MAX_KEEPALIVE_INTERVAL = 3;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053070 private BgpPeer bgpPeer;
71 private BgpId thisbgpId;
Shashikanth VH9f8afb42015-11-04 18:00:30 +053072 private Channel channel;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053073 private BgpKeepAliveTimer keepAliveTimer = null;
Shashikanth VH6de20d32015-10-09 12:04:13 +053074 private short peerHoldTime = 0;
75 private short negotiatedHoldTime = 0;
Shashikanth VH9f8afb42015-11-04 18:00:30 +053076 private long peerAsNum;
Shashikanth VH6de20d32015-10-09 12:04:13 +053077 private int peerIdentifier;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053078 private BgpPacketStatsImpl bgpPacketStats;
Shashikanth VH6de20d32015-10-09 12:04:13 +053079 static final int MAX_WRONG_COUNT_PACKET = 5;
Vidyashree Ramaee293252015-11-18 17:00:11 +053080 static final byte MULTI_PROTOCOL_EXTN_CAPA_TYPE = 1;
81 static final byte FOUR_OCTET_AS_NUM_CAPA_TYPE = 65;
82 static final int AS_TRANS = 23456;
83 static final int MAX_AS2_NUM = 65535;
84 static final short AFI = 16388;
85 static final byte RES = 0;
86 static final byte SAFI = 71;
Shashikanth VH6de20d32015-10-09 12:04:13 +053087
88 // State needs to be volatile because the HandshakeTimeoutHandler
89 // needs to check if the handshake is complete
90 private volatile ChannelState state;
91
92 // When a bgp peer with a ip addresss is found (i.e we already have a
93 // connected peer with the same ip), the new peer is immediately
94 // disconnected. At that point netty callsback channelDisconnected() which
Shashikanth VH9f8afb42015-11-04 18:00:30 +053095 // proceeds to cleaup peer state - we need to ensure that it does not
96 // cleanup
Shashikanth VH6de20d32015-10-09 12:04:13 +053097 // peer state for the older (still connected) peer
98 private volatile Boolean duplicateBGPIdFound;
99 // Indicates the bgp version used by this bgp peer
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530100 protected BgpVersion bgpVersion;
101 private BgpController bgpController;
102 protected BgpFactory factory4;
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530103 private boolean isIbgpSession;
104 private BgpSessionInfoImpl sessionInfo;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530105 private BgpPeerManagerImpl peerManager;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530106 private InetSocketAddress inetAddress;
107 private IpAddress ipAddress;
108 private SocketAddress address;
109 private String peerAddr;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530110 private BgpCfg bgpconfig;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530111
Satish Ke107e662015-09-21 19:00:17 +0530112 /**
113 * Create a new unconnected BGPChannelHandler.
114 *
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530115 * @param bgpController bgp controller
Satish Ke107e662015-09-21 19:00:17 +0530116 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530117 BgpChannelHandler(BgpController bgpController) {
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530118 this.bgpController = bgpController;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530119 this.peerManager = (BgpPeerManagerImpl) bgpController.peerManager();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530120 this.state = ChannelState.IDLE;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530121 this.factory4 = Controller.getBgpMessageFactory4();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530122 this.duplicateBGPIdFound = Boolean.FALSE;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530123 this.bgpPacketStats = new BgpPacketStatsImpl();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530124 this.bgpconfig = bgpController.getConfig();
Satish Ke107e662015-09-21 19:00:17 +0530125 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530126
127 // To disconnect peer session.
128 public void disconnectPeer() {
129 bgpPeer.disconnectPeer();
130 }
131
132 // *************************
133 // Channel State Machine
134 // *************************
135
136 /**
137 * The state machine for handling the peer/channel state. All state transitions should happen from within the state
138 * machine (and not from other parts of the code)
139 */
140 enum ChannelState {
141 /**
142 * Initial state before channel is connected.
143 */
144 IDLE(false) {
145
146 },
147
148 OPENSENT(false) {
149 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530150 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530151 log.debug("message received in OPENSENT state");
152 // check for OPEN message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530153 if (m.getType() != BgpType.OPEN) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530154 // When the message type is not keep alive message increment the wrong packet statistics
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530155 h.processUnknownMsg(BgpErrorType.FINITE_STATE_MACHINE_ERROR,
156 BgpErrorType.RECEIVE_UNEXPECTED_MESSAGE_IN_OPENSENT_STATE,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530157 m.getType().getType());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530158 log.debug("Message is not OPEN message");
159 } else {
160 log.debug("Sending keep alive message in OPENSENT state");
161 h.bgpPacketStats.addInPacket();
162
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530163 BgpOpenMsg pOpenmsg = (BgpOpenMsg) m;
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530164 h.peerIdentifier = pOpenmsg.getBgpId();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530165
166 // validate capabilities and open msg
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530167 if (h.openMsgValidation(h, pOpenmsg)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530168 if (h.connectionCollisionDetection(BgpPeerCfg.State.OPENCONFIRM,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530169 h.peerIdentifier, h.peerAddr)) {
170 h.channel.close();
171 return;
172 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530173 log.debug("Sending handshake OPEN message");
174
175 /*
176 * RFC 4271, section 4.2: Upon receipt of an OPEN message, a BGP speaker MUST calculate the
177 * value of the Hold Timer by using the smaller of its configured Hold Time and the Hold Time
178 * received in the OPEN message
179 */
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530180 h.peerHoldTime = pOpenmsg.getHoldTime();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530181 if (h.peerHoldTime < h.bgpconfig.getHoldTime()) {
182 h.channel.getPipeline().replace("holdTime",
183 "holdTime",
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530184 new ReadTimeoutHandler(BgpPipelineFactory.TIMER,
Shashikanth VH6de20d32015-10-09 12:04:13 +0530185 h.peerHoldTime));
186 }
187
188 log.info("Hold Time : " + h.peerHoldTime);
189
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530190 // update AS number
191 h.peerAsNum = pOpenmsg.getAsNumber();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530192 }
193
194 // Send keepalive message to peer.
195 h.sendKeepAliveMessage();
196 h.bgpPacketStats.addOutPacket();
197 h.setState(OPENCONFIRM);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530198 h.bgpconfig.setPeerConnState(h.peerAddr, BgpPeerCfg.State.OPENCONFIRM);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530199 }
200 }
201 },
202
203 OPENWAIT(false) {
204 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530205 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530206 log.debug("Message received in OPEN WAIT State");
207
208 // check for open message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530209 if (m.getType() != BgpType.OPEN) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530210 // When the message type is not open message increment the wrong packet statistics
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530211 h.processUnknownMsg(BgpErrorType.FINITE_STATE_MACHINE_ERROR, BgpErrorType.UNSPECIFIED_ERROR,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530212 m.getType().getType());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530213 log.debug("Message is not OPEN message");
214 } else {
215 h.bgpPacketStats.addInPacket();
216
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530217 BgpOpenMsg pOpenmsg = (BgpOpenMsg) m;
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530218 h.peerIdentifier = pOpenmsg.getBgpId();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530219
220 // Validate open message
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530221 if (h.openMsgValidation(h, pOpenmsg)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530222 if (h.connectionCollisionDetection(BgpPeerCfg.State.OPENSENT,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530223 h.peerIdentifier, h.peerAddr)) {
224 h.channel.close();
225 return;
226 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530227 log.debug("Sending handshake OPEN message");
228
229 /*
230 * RFC 4271, section 4.2: Upon receipt of an OPEN message, a BGP speaker MUST calculate the
231 * value of the Hold Timer by using the smaller of its configured Hold Time and the Hold Time
232 * received in the OPEN message
233 */
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530234 h.peerHoldTime = pOpenmsg.getHoldTime();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530235 if (h.peerHoldTime < h.bgpconfig.getHoldTime()) {
236 h.channel.getPipeline().replace("holdTime",
237 "holdTime",
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530238 new ReadTimeoutHandler(BgpPipelineFactory.TIMER,
Shashikanth VH6de20d32015-10-09 12:04:13 +0530239 h.peerHoldTime));
240 }
241
242 log.debug("Hold Time : " + h.peerHoldTime);
243
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530244 // update AS number
245 h.peerAsNum = pOpenmsg.getAsNumber();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530246
247 h.sendHandshakeOpenMessage();
248 h.bgpPacketStats.addOutPacket();
249 h.setState(OPENCONFIRM);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530250 h.bgpconfig.setPeerConnState(h.peerAddr, BgpPeerCfg.State.OPENCONFIRM);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530251 }
252 }
253 }
254 },
255
256 OPENCONFIRM(false) {
257 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530258 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530259 log.debug("Message received in OPENCONFIRM state");
260 // check for keep alive message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530261 if (m.getType() != BgpType.KEEP_ALIVE) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530262 // When the message type is not keep alive message handle the wrong packet
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530263 h.processUnknownMsg(BgpErrorType.FINITE_STATE_MACHINE_ERROR,
264 BgpErrorType.RECEIVE_UNEXPECTED_MESSAGE_IN_OPENCONFIRM_STATE,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530265 m.getType().getType());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530266 log.debug("Message is not KEEPALIVE message");
267 } else {
268
269 // Set the peer connected status
270 h.bgpPacketStats.addInPacket();
271 log.debug("Sending keep alive message in OPENCONFIRM state");
272
273 final InetSocketAddress inetAddress = (InetSocketAddress) h.address;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530274 h.thisbgpId = BgpId.bgpId(IpAddress.valueOf(inetAddress.getAddress()));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530275
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530276 // set session parameters
277 h.negotiatedHoldTime = (h.peerHoldTime < h.bgpconfig.getHoldTime()) ? h.peerHoldTime
278 : h.bgpconfig.getHoldTime();
279 h.sessionInfo = new BgpSessionInfoImpl(h.thisbgpId, h.bgpVersion, h.peerAsNum, h.peerHoldTime,
280 h.peerIdentifier, h.negotiatedHoldTime, h.isIbgpSession);
281
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530282 h.bgpPeer = h.peerManager.getBgpPeerInstance(h.bgpController, h.sessionInfo, h.bgpPacketStats);
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530283 // set the status of bgp as connected
Shashikanth VH6de20d32015-10-09 12:04:13 +0530284 h.bgpPeer.setConnected(true);
285 h.bgpPeer.setChannel(h.channel);
286
Shashikanth VH6de20d32015-10-09 12:04:13 +0530287 /*
288 * RFC 4271, When an OPEN message is received, sends a KEEPALIVE message, If the negotiated hold
289 * time value is zero, then the HoldTimer and KeepaliveTimer are not started. A reasonable maximum
290 * time between KEEPALIVE messages would be one third of the Hold Time interval.
291 */
Shashikanth VH6de20d32015-10-09 12:04:13 +0530292
293 if (h.negotiatedHoldTime != 0) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530294 h.keepAliveTimer = new BgpKeepAliveTimer(h,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530295 (h.negotiatedHoldTime / BGP_MAX_KEEPALIVE_INTERVAL));
Shashikanth VHdae80402015-11-20 14:20:33 +0530296 } else {
297 h.sendKeepAliveMessage();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530298 }
299
300 h.bgpPacketStats.addOutPacket();
301
302 // set the state handshake completion.
303 h.setHandshakeComplete(true);
304
305 if (!h.peerManager.addConnectedPeer(h.thisbgpId, h.bgpPeer)) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530306 disconnectDuplicate(h);
307 } else {
308 h.setState(ESTABLISHED);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530309 h.bgpconfig.setPeerConnState(h.peerAddr, BgpPeerCfg.State.ESTABLISHED);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530310 }
311 }
312 }
313 },
314
315 ESTABLISHED(true) {
316 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530317 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530318 log.debug("Message received in established state " + m.getType());
319 // dispatch the message
320 h.dispatchMessage(m);
321 }
322 };
323
324 private boolean handshakeComplete;
325
326 ChannelState(boolean handshakeComplete) {
327 this.handshakeComplete = handshakeComplete;
328 }
329
330 /**
331 * Is this a state in which the handshake has completed?
332 *
333 * @return true if the handshake is complete
334 */
335 public boolean isHandshakeComplete() {
336 return this.handshakeComplete;
337 }
338
339 /**
340 * Disconnect duplicate peer connection.
341 *
342 * @param h channel handler
343 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530344 protected void disconnectDuplicate(BgpChannelHandler h) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530345 log.error("Duplicated BGP IP or incompleted cleanup - " + "" + "disconnecting channel {}",
346 h.getPeerInfoString());
347 h.duplicateBGPIdFound = Boolean.TRUE;
348 h.channel.disconnect();
349 }
350
351 // set handshake completion status
352 public void setHandshakeComplete(boolean handshakeComplete) {
353 this.handshakeComplete = handshakeComplete;
354 }
355
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530356 void processBgpMessage(BgpChannelHandler bgpChannelHandler, BgpMessage pm)
357 throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530358 // TODO Auto-generated method stub
359 log.debug("BGP message stub");
360 }
361
362 }
363
364 // *************************
365 // Channel handler methods
366 // *************************
367
368 @Override
369 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
370
371 channel = e.getChannel();
372 log.info("BGP connected from {}", channel.getRemoteAddress());
373
374 address = channel.getRemoteAddress();
375 if (!(address instanceof InetSocketAddress)) {
376 throw new IOException("Invalid peer connection.");
377 }
378
Shashikanth VH6de20d32015-10-09 12:04:13 +0530379
380 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530381 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530382
Shashikanth VH6de20d32015-10-09 12:04:13 +0530383
384 // if connection is already established close channel
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530385 if (peerManager.isPeerConnected(BgpId.bgpId(IpAddress.valueOf(peerAddr)))) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530386 log.debug("Duplicate connection received, peer {}", peerAddr);
387 channel.close();
388 return;
389 }
390
391 if (null != channel.getPipeline().get("PassiveHandler")) {
392 log.info("BGP handle connection request from peer");
393 // Wait for open message from bgp peer
394 setState(ChannelState.OPENWAIT);
395 } else if (null != channel.getPipeline().get("ActiveHandler")) {
396 log.info("BGP handle connection response from peer");
397
398 sendHandshakeOpenMessage();
399 bgpPacketStats.addOutPacket();
400 setState(ChannelState.OPENSENT);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530401 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.OPENSENT);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530402 }
403 }
404
405 @Override
406 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
407
408 channel = e.getChannel();
409 log.info("BGP disconnected callback for bgp:{}. Cleaning up ...", getPeerInfoString());
410
411 address = channel.getRemoteAddress();
412 if (!(address instanceof InetSocketAddress)) {
413 throw new IOException("Invalid peer connection.");
414 }
415
416 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530417 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530418
419 if (thisbgpId != null) {
420 if (!duplicateBGPIdFound) {
421 // if the disconnected peer (on this ChannelHandler)
422 // was not one with a duplicate, it is safe to remove all
423 // state for it at the controller. Notice that if the disconnected
424 // peer was a duplicate-ip, calling the method below would clear
425 // all state for the original peer (with the same ip),
426 // which we obviously don't want.
427 log.debug("{}:removal called", getPeerInfoString());
428 if (bgpPeer != null) {
Shashikanth VH3fe37982015-11-30 11:50:07 +0530429 BgpPeerImpl peer = (BgpPeerImpl) bgpPeer;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530430 peerManager.removeConnectedPeer(thisbgpId);
Shashikanth VH3fe37982015-11-30 11:50:07 +0530431 peer.updateLocalRIBOnPeerDisconnect();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530432 }
Shashikanth VH447c6b02015-11-25 21:25:35 +0530433
434 // Retry connection if connection is lost to bgp speaker/peer
435 if ((channel != null) && (null != channel.getPipeline().get("ActiveHandler"))) {
436 BgpConnectPeerImpl connectPeer;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530437 BgpPeerCfg.State peerCfgState;
Shashikanth VH447c6b02015-11-25 21:25:35 +0530438
439 peerCfgState = bgpconfig.getPeerConnState(peerAddr);
440 // on session disconnect using configuration, do not retry
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530441 if (!peerCfgState.equals(BgpPeerCfg.State.IDLE)) {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530442 log.debug("Connection reset by peer, retry, STATE:{}", peerCfgState);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530443 BgpPeerConfig peerConfig = (BgpPeerConfig) bgpconfig.displayPeers(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530444
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530445 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530446 connectPeer = new BgpConnectPeerImpl(bgpController, peerAddr, Controller.getBgpPortNum());
447 peerConfig.setConnectPeer(connectPeer);
448 }
449 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530450 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530451 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530452 } else {
453 // A duplicate was disconnected on this ChannelHandler,
454 // this is the same peer reconnecting, but the original state was
455 // not cleaned up - XXX check liveness of original ChannelHandler
456 log.debug("{}:duplicate found", getPeerInfoString());
457 duplicateBGPIdFound = Boolean.FALSE;
458 }
459
460 if (null != keepAliveTimer) {
461 keepAliveTimer.getKeepAliveTimer().cancel();
462 }
463 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530464 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530465 log.warn("No bgp ip in channelHandler registered for " + "disconnected peer {}", getPeerInfoString());
466 }
467 }
468
469 @Override
470 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
471
472 log.info("[exceptionCaught]: " + e.toString());
473
474 if (e.getCause() instanceof ReadTimeoutException) {
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530475 // device timeout
476 log.error("Disconnecting device {} due to read timeout", getPeerInfoString());
477 sendNotification(BgpErrorType.HOLD_TIMER_EXPIRED, (byte) 0, null);
478 state = ChannelState.IDLE;
479 ctx.getChannel().close();
480 return;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530481 } else if (e.getCause() instanceof ClosedChannelException) {
482 log.debug("Channel for bgp {} already closed", getPeerInfoString());
483 } else if (e.getCause() instanceof IOException) {
484 log.error("Disconnecting peer {} due to IO Error: {}", getPeerInfoString(), e.getCause().getMessage());
485 if (log.isDebugEnabled()) {
486 // still print stack trace if debug is enabled
487 log.debug("StackTrace for previous Exception: ", e.getCause());
488 }
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530489 ctx.getChannel().close();
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530490 } else if (e.getCause() instanceof BgpParseException) {
Shashikanth VHdae80402015-11-20 14:20:33 +0530491 byte[] data = new byte[] {};
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530492 BgpParseException errMsg = (BgpParseException) e.getCause();
Shashikanth VHdae80402015-11-20 14:20:33 +0530493 byte errorCode = errMsg.getErrorCode();
494 byte errorSubCode = errMsg.getErrorSubCode();
495 ChannelBuffer tempCb = errMsg.getData();
496 if (tempCb != null) {
497 int dataLength = tempCb.capacity();
498 data = new byte[dataLength];
499 tempCb.readBytes(data, 0, dataLength);
500 }
501 sendNotification(errorCode, errorSubCode, data);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530502 } else if (e.getCause() instanceof RejectedExecutionException) {
503 log.warn("Could not process message: queue full");
504 } else {
505 log.error("Error while processing message from peer " + getPeerInfoString() + "state " + this.state);
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530506 ctx.getChannel().close();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530507 }
508 }
509
510 @Override
511 public String toString() {
512 return getPeerInfoString();
513 }
514
515 @Override
516 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
517 if (e.getMessage() instanceof List) {
518 @SuppressWarnings("Unchecked")
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530519 List<BgpMessage> msglist = (List<BgpMessage>) e.getMessage();
520 for (BgpMessage pm : msglist) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530521 // Do the actual packet processing
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530522 state.processBgpMessage(this, pm);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530523 }
524 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530525 state.processBgpMessage(this, (BgpMessage) e.getMessage());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530526 }
527 }
528
Shashikanth VH447c6b02015-11-25 21:25:35 +0530529 /**
530 * Check for connection collision.
531 *
532 * @param state connection state
533 * @param peerIdentifier BGP peer identifier
534 * @param peerAddr BGP peer address
535 * @return true if bgp spreakers initiated connection
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530536 * @throws BgpParseException on error while procession collision detection
Shashikanth VH447c6b02015-11-25 21:25:35 +0530537 * @throws IOException on error while procession collision detection
538 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530539 public boolean connectionCollisionDetection(BgpPeerCfg.State state, int peerIdentifier, String peerAddr)
540 throws IOException, BgpParseException {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530541 /*
542 * RFC 4271, Section 6.8, Based on the value of the BGP identifier, a convention is established for detecting
543 * which BGP connection is to be preserved when a collision occurs. The convention is to compare the BGP
544 * Identifiers of the peers involved in the collision and to retain only the connection initiated by the BGP
545 * speaker with the higher-valued BGP Identifier..
546 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530547 BgpPeerCfg.State currentState = bgpconfig.getPeerConnState(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530548 if (currentState.equals(state)) {
549 if (((Ip4Address.valueOf(bgpconfig.getRouterId())).compareTo(Ip4Address.valueOf(peerIdentifier))) > 0) {
550 // send notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530551 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_COLLISION_RESOLUTION, null);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530552 log.debug("Connection collision detected, local id: {}, peer id: {}, peer state:{}, in state:{}",
553 (Ip4Address.valueOf(bgpconfig.getRouterId())), (Ip4Address.valueOf(peerIdentifier)),
554 currentState, state);
555 return true;
556 }
557 }
558
559 return false;
560 }
561
Shashikanth VH6de20d32015-10-09 12:04:13 +0530562 // *************************
563 // Channel utility methods
564 // *************************
565 /**
566 * Set handshake status.
567 *
568 * @param handshakeComplete handshake complete status
569 */
570 public void setHandshakeComplete(boolean handshakeComplete) {
571 this.state.setHandshakeComplete(handshakeComplete);
572 }
573
574 /**
575 * Is this a state in which the handshake has completed?
576 *
577 * @return true if the handshake is complete
578 */
579 public boolean isHandshakeComplete() {
580 return state.isHandshakeComplete();
581 }
582
583 /**
584 * To handle the BGP message.
585 *
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530586 * @param m bgp message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530587 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530588 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530589 private void dispatchMessage(BgpMessage m) throws BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530590 bgpPacketStats.addInPacket();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530591 bgpController.processBGPPacket(thisbgpId, m);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530592 }
593
594 /**
595 * Return a string describing this peer based on the already available information (ip address and/or remote
596 * socket).
597 *
598 * @return display string
599 */
600 private String getPeerInfoString() {
601 if (bgpPeer != null) {
602 return bgpPeer.toString();
603 }
604 String channelString;
605 if (channel == null || channel.getRemoteAddress() == null) {
606 channelString = "?";
607 } else {
608 channelString = channel.getRemoteAddress().toString();
609 }
610 String bgpIpString;
611 // TODO: implement functionality to get bgp id string
612 bgpIpString = "?";
613 return String.format("[%s BGP-IP[%s]]", channelString, bgpIpString);
614 }
615
616 /**
617 * Update the channels state. Only called from the state machine. TODO: enforce restricted state transitions
618 *
619 * @param state
620 */
621 private void setState(ChannelState state) {
622 this.state = state;
623 }
624
625 /**
626 * get packet statistics.
627 *
628 * @return packet statistics
629 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530630 public BgpPacketStatsImpl getBgpPacketStats() {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530631 return bgpPacketStats;
632 }
633
634 /**
635 * Send handshake open message to the peer.
636 *
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530637 * @throws IOException, BgpParseException
Shashikanth VH6de20d32015-10-09 12:04:13 +0530638 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530639 private void sendHandshakeOpenMessage() throws IOException, BgpParseException {
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530640 int bgpId;
641
Shashikanth VHcea18d32015-12-04 15:45:14 +0530642 InetSocketAddress localAddress = (InetSocketAddress) channel.getLocalAddress();
643
644 bgpId = Ip4Address.valueOf(IpAddress.valueOf(localAddress.getAddress()).toString()).toInt();
645 BgpMessage msg = factory4.openMessageBuilder().setAsNumber((short) peerAsNum)
Shashikanth VH447c6b02015-11-25 21:25:35 +0530646 .setHoldTime(bgpconfig.getHoldTime()).setBgpId(bgpId).setLsCapabilityTlv(bgpconfig.getLsCapability())
647 .setLargeAsCapabilityTlv(bgpconfig.getLargeASCapability()).build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530648 log.debug("Sending open message to {}", channel.getRemoteAddress());
649 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530650
651 }
652
653 /**
Shashikanth VHdae80402015-11-20 14:20:33 +0530654 * Send notification message to peer.
655 *
656 * @param errorCode error code send in notification
657 * @param errorSubCode sub error code send in notification
658 * @param data data to send in notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530659 * @throws IOException, BgpParseException while building message
Shashikanth VHdae80402015-11-20 14:20:33 +0530660 */
661 private void sendNotification(byte errorCode, byte errorSubCode, byte[] data)
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530662 throws IOException, BgpParseException {
663 BgpMessage msg = factory4.notificationMessageBuilder().setErrorCode(errorCode)
Shashikanth VH447c6b02015-11-25 21:25:35 +0530664 .setErrorSubCode(errorSubCode).setData(data).build();
Shashikanth VHdae80402015-11-20 14:20:33 +0530665 log.debug("Sending notification message to {}", channel.getRemoteAddress());
666 channel.write(Collections.singletonList(msg));
667 }
668
669 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530670 * Send keep alive message.
671 *
672 * @throws IOException when channel is disconnected
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530673 * @throws BgpParseException while building keep alive message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530674 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530675 synchronized void sendKeepAliveMessage() throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530676
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530677 BgpMessage msg = factory4.keepaliveMessageBuilder().build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530678 log.debug("Sending keepalive message to {}", channel.getRemoteAddress());
679 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530680 }
681
682 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530683 * Process unknown BGP message received.
684 *
Shashikanth VHdae80402015-11-20 14:20:33 +0530685 * @param errorCode error code
686 * @param errorSubCode error sub code
687 * @param data message type
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530688 * @throws BgpParseException while processing error messsage
Shashikanth VHdae80402015-11-20 14:20:33 +0530689 * @throws IOException while processing error message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530690 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530691 public void processUnknownMsg(byte errorCode, byte errorSubCode, byte data) throws BgpParseException, IOException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530692 log.debug("UNKNOWN message received");
Shashikanth VHdae80402015-11-20 14:20:33 +0530693 byte[] byteArray = new byte[1];
694 byteArray[0] = data;
695 sendNotification(errorCode, errorSubCode, byteArray);
696 channel.close();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530697 }
698
699 /**
Vidyashree Ramaee293252015-11-18 17:00:11 +0530700 * BGP open message validation.
Shashikanth VH6de20d32015-10-09 12:04:13 +0530701 *
702 * @param h channel handler
Vidyashree Ramaee293252015-11-18 17:00:11 +0530703 * @param openMsg open message
704 * @return true if valid message, otherwise false
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530705 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530706 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530707 public boolean openMsgValidation(BgpChannelHandler h, BgpOpenMsg openMsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530708 boolean result;
709
710 // Validate BGP ID
711 result = bgpIdValidation(openMsg);
712 if (!result) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530713 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_BGP_IDENTIFIER, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530714 }
715
Vidyashree Ramaee293252015-11-18 17:00:11 +0530716
717 // Validate hold timer
718 if ((openMsg.getHoldTime() != 0) && (openMsg.getHoldTime() < BGP_MIN_HOLDTIME)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530719 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNACCEPTABLE_HOLD_TIME, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530720 }
721
722 // Validate capabilities
723 result = capabilityValidation(h, openMsg);
724 return result;
725 }
726
727 /**
728 * Capability Validation.
729 *
730 * @param h channel handler
731 * @param openmsg open message
732 * @return success or failure
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530733 * @throws BgpParseException
Vidyashree Ramaee293252015-11-18 17:00:11 +0530734 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530735 private boolean capabilityValidation(BgpChannelHandler h, BgpOpenMsg openmsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530736 log.debug("capabilityValidation");
737
738 boolean isMultiProtocolcapabilityExists = false;
739 boolean isFourOctetCapabilityExits = false;
740 int capAsNum = 0;
741
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530742 List<BgpValueType> capabilityTlv = openmsg.getCapabilityTlv();
743 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
744 List<BgpValueType> unSupportedCapabilityTlv = new LinkedList<>();
745 ListIterator<BgpValueType> unSupportedCaplistIterator = unSupportedCapabilityTlv.listIterator();
746 BgpValueType tempTlv;
Vidyashree Ramaee293252015-11-18 17:00:11 +0530747 boolean isLargeAsCapabilityCfg = h.bgpconfig.getLargeASCapability();
748 boolean isLsCapabilityCfg = h.bgpconfig.getLsCapability();
749
750 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530751 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530752 if (tlv.getType() == MULTI_PROTOCOL_EXTN_CAPA_TYPE) {
753 isMultiProtocolcapabilityExists = true;
754 }
755 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
756 isFourOctetCapabilityExits = true;
757 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
758 }
759 }
760
761 if (isFourOctetCapabilityExits) {
762 if (capAsNum > MAX_AS2_NUM) {
763 if (openmsg.getAsNumber() != AS_TRANS) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530764 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530765 }
766 } else {
767 if (capAsNum != openmsg.getAsNumber()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530768 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530769 }
770 }
771 }
772
773 if ((isLsCapabilityCfg)) {
774 if (!isMultiProtocolcapabilityExists) {
775 tempTlv = new MultiProtocolExtnCapabilityTlv(AFI, RES, SAFI);
776 unSupportedCapabilityTlv.add(tempTlv);
777 }
778 }
779
780 if ((isLargeAsCapabilityCfg)) {
781 if (!isFourOctetCapabilityExits) {
782 tempTlv = new FourOctetAsNumCapabilityTlv(h.bgpconfig.getAsNumber());
783 unSupportedCapabilityTlv.add(tempTlv);
784 }
785 }
786
787 if (unSupportedCaplistIterator.hasNext()) {
788 ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
789 while (unSupportedCaplistIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530790 BgpValueType tlv = unSupportedCaplistIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530791 tlv.write(buffer);
792 }
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530793 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNSUPPORTED_CAPABILITY, buffer);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530794 } else {
795 return true;
796 }
797 }
798
799 /**
800 * AS Number Validation.
801 *
802 * @param h channel Handler
803 * @param openMsg open message
804 * @return true or false
805 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530806 private boolean asNumberValidation(BgpChannelHandler h, BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530807 log.debug("AS Num validation");
808
809 int capAsNum = 0;
810 boolean isFourOctetCapabilityExits = false;
811
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530812 BgpPeerCfg peerCfg = h.bgpconfig.displayPeers(peerAddr);
813 List<BgpValueType> capabilityTlv = openMsg.getCapabilityTlv();
814 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530815
816 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530817 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530818 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
819 isFourOctetCapabilityExits = true;
820 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
821 }
822 }
823
824 if (peerCfg.getAsNumber() > MAX_AS2_NUM) {
825 if (openMsg.getAsNumber() != AS_TRANS) {
826 return false;
827 }
828
829 if (!isFourOctetCapabilityExits) {
830 return false;
831 }
832
833 if (peerCfg.getAsNumber() != capAsNum) {
834 return false;
835 }
836
837 isIbgpSession = peerCfg.getIsIBgp();
838 if (isIbgpSession) {
839 // IBGP - AS number should be same for Peer and local if it is IBGP
840 if (h.bgpconfig.getAsNumber() != capAsNum) {
841 return false;
842 }
843 }
844 } else {
845
846 if (openMsg.getAsNumber() != peerCfg.getAsNumber()) {
847 return false;
848 }
849
850 if (isFourOctetCapabilityExits) {
851 if (capAsNum != peerCfg.getAsNumber()) {
852 return false;
853 }
854 }
855
856 isIbgpSession = peerCfg.getIsIBgp();
857 if (isIbgpSession) {
858 // IBGP - AS number should be same for Peer and local if it is IBGP
859 if (openMsg.getAsNumber() != h.bgpconfig.getAsNumber()) {
860 return false;
861 }
862 }
863 }
864 return true;
865 }
866
867 /**
868 * Validates BGP ID.
869 *
870 * @param openMsg open message
871 * @return true or false
872 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530873 private boolean bgpIdValidation(BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530874 String openMsgBgpId = Ip4Address.valueOf(openMsg.getBgpId()).toString();
875
876 InetAddress ipAddress;
877 try {
878 ipAddress = InetAddress.getByName(openMsgBgpId);
879 if (ipAddress.isMulticastAddress()) {
880 return false;
881 }
882 } catch (UnknownHostException e) {
883 log.debug("InetAddress convertion failed");
884 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530885 return true;
886 }
887}