blob: 8ffbaa7ffb8af2b13e6482e97b816b8c62268d0c [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
Vidyashree Ramaee293252015-11-18 17:00:11 +053019import org.jboss.netty.buffer.ChannelBuffer;
20import org.jboss.netty.buffer.ChannelBuffers;
Shashikanth VH6de20d32015-10-09 12:04:13 +053021import org.jboss.netty.channel.Channel;
22import org.jboss.netty.channel.ChannelHandlerContext;
23import org.jboss.netty.channel.ChannelStateEvent;
24import org.jboss.netty.channel.ExceptionEvent;
25import org.jboss.netty.channel.MessageEvent;
Satish Ke107e662015-09-21 19:00:17 +053026import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
Shashikanth VH6de20d32015-10-09 12:04:13 +053027import org.jboss.netty.handler.timeout.ReadTimeoutException;
28import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
Shashikanth VH9f8afb42015-11-04 18:00:30 +053029import org.onlab.packet.Ip4Address;
Shashikanth VH6de20d32015-10-09 12:04:13 +053030import org.onlab.packet.IpAddress;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053031import org.onosproject.bgp.controller.BgpCfg;
32import org.onosproject.bgp.controller.BgpController;
33import org.onosproject.bgp.controller.BgpId;
34import org.onosproject.bgp.controller.BgpPeer;
35import org.onosproject.bgp.controller.BgpPeerCfg;
36import org.onosproject.bgp.controller.impl.BgpControllerImpl.BgpPeerManagerImpl;
37import org.onosproject.bgpio.exceptions.BgpParseException;
38import org.onosproject.bgpio.protocol.BgpFactory;
39import org.onosproject.bgpio.protocol.BgpMessage;
40import org.onosproject.bgpio.protocol.BgpOpenMsg;
41import org.onosproject.bgpio.protocol.BgpType;
42import org.onosproject.bgpio.protocol.BgpVersion;
43import org.onosproject.bgpio.types.BgpErrorType;
44import org.onosproject.bgpio.types.BgpValueType;
Vidyashree Ramaee293252015-11-18 17:00:11 +053045import org.onosproject.bgpio.types.FourOctetAsNumCapabilityTlv;
46import org.onosproject.bgpio.types.MultiProtocolExtnCapabilityTlv;
Shashikanth VH6de20d32015-10-09 12:04:13 +053047import org.slf4j.Logger;
48import org.slf4j.LoggerFactory;
Satish Ke107e662015-09-21 19:00:17 +053049
Jonathan Hart51539b82015-10-29 09:53:04 -070050import java.io.IOException;
51import java.net.InetAddress;
52import java.net.InetSocketAddress;
53import java.net.SocketAddress;
54import java.net.UnknownHostException;
55import java.nio.channels.ClosedChannelException;
56import java.util.Collections;
57import java.util.LinkedList;
58import java.util.List;
59import java.util.ListIterator;
60import java.util.concurrent.RejectedExecutionException;
61
Satish Ke107e662015-09-21 19:00:17 +053062/**
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
Jonathan Hart51539b82015-10-29 09:53:04 -070098 private volatile Boolean duplicateBgpIdFound;
Shashikanth VH6de20d32015-10-09 12:04:13 +053099 // 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();
Jonathan Hart51539b82015-10-29 09:53:04 -0700122 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());
Jonathan Hart51539b82015-10-29 09:53:04 -0700347 h.duplicateBgpIdFound = Boolean.TRUE;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530348 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
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530364 //Stop keepalive timer
365 private void stopKeepAliveTimer() {
366 if ((keepAliveTimer != null) && (keepAliveTimer.getKeepAliveTimer() != null)) {
367 keepAliveTimer.getKeepAliveTimer().cancel();
368 }
369 }
370
Shashikanth VH6de20d32015-10-09 12:04:13 +0530371 // *************************
372 // Channel handler methods
373 // *************************
374
375 @Override
376 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
377
378 channel = e.getChannel();
379 log.info("BGP connected from {}", channel.getRemoteAddress());
380
381 address = channel.getRemoteAddress();
382 if (!(address instanceof InetSocketAddress)) {
383 throw new IOException("Invalid peer connection.");
384 }
385
Shashikanth VH97e571e2016-01-05 12:15:14 +0530386 // Connection should establish only if local ip and Autonomous system number is configured.
387 if (bgpconfig.getState() != BgpCfg.State.IP_AS_CONFIGURED) {
388 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_REJECTED, null);
389 channel.close();
390 log.info("BGP local AS and router ID not configured");
391 return;
392 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530393
394 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530395 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530396
Shashikanth VH97e571e2016-01-05 12:15:14 +0530397 // if peer is not configured disconnect session
398 if (!bgpconfig.isPeerConfigured(peerAddr)) {
399 log.debug("Peer is not configured {}", peerAddr);
400 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_REJECTED, null);
401 channel.close();
402 return;
403 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530404
405 // if connection is already established close channel
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530406 if (peerManager.isPeerConnected(BgpId.bgpId(IpAddress.valueOf(peerAddr)))) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530407 log.debug("Duplicate connection received, peer {}", peerAddr);
408 channel.close();
409 return;
410 }
411
412 if (null != channel.getPipeline().get("PassiveHandler")) {
413 log.info("BGP handle connection request from peer");
414 // Wait for open message from bgp peer
415 setState(ChannelState.OPENWAIT);
416 } else if (null != channel.getPipeline().get("ActiveHandler")) {
417 log.info("BGP handle connection response from peer");
418
419 sendHandshakeOpenMessage();
420 bgpPacketStats.addOutPacket();
421 setState(ChannelState.OPENSENT);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530422 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.OPENSENT);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530423 }
424 }
425
426 @Override
427 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
428
429 channel = e.getChannel();
430 log.info("BGP disconnected callback for bgp:{}. Cleaning up ...", getPeerInfoString());
431
432 address = channel.getRemoteAddress();
433 if (!(address instanceof InetSocketAddress)) {
434 throw new IOException("Invalid peer connection.");
435 }
436
437 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530438 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530439
440 if (thisbgpId != null) {
Jonathan Hart51539b82015-10-29 09:53:04 -0700441 if (!duplicateBgpIdFound) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530442 // if the disconnected peer (on this ChannelHandler)
443 // was not one with a duplicate, it is safe to remove all
444 // state for it at the controller. Notice that if the disconnected
445 // peer was a duplicate-ip, calling the method below would clear
446 // all state for the original peer (with the same ip),
447 // which we obviously don't want.
448 log.debug("{}:removal called", getPeerInfoString());
449 if (bgpPeer != null) {
Shashikanth VH3fe37982015-11-30 11:50:07 +0530450 BgpPeerImpl peer = (BgpPeerImpl) bgpPeer;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530451 peerManager.removeConnectedPeer(thisbgpId);
Jonathan Hart51539b82015-10-29 09:53:04 -0700452 peer.updateLocalRibOnPeerDisconnect();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530453 }
Shashikanth VH447c6b02015-11-25 21:25:35 +0530454
455 // Retry connection if connection is lost to bgp speaker/peer
456 if ((channel != null) && (null != channel.getPipeline().get("ActiveHandler"))) {
457 BgpConnectPeerImpl connectPeer;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530458 BgpPeerCfg.State peerCfgState;
Shashikanth VH447c6b02015-11-25 21:25:35 +0530459
460 peerCfgState = bgpconfig.getPeerConnState(peerAddr);
461 // on session disconnect using configuration, do not retry
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530462 if (!peerCfgState.equals(BgpPeerCfg.State.IDLE)) {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530463 log.debug("Connection reset by peer, retry, STATE:{}", peerCfgState);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530464 BgpPeerConfig peerConfig = (BgpPeerConfig) bgpconfig.displayPeers(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530465
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530466 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530467 connectPeer = new BgpConnectPeerImpl(bgpController, peerAddr, Controller.getBgpPortNum());
468 peerConfig.setConnectPeer(connectPeer);
469 }
470 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530471 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530472 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530473 } else {
474 // A duplicate was disconnected on this ChannelHandler,
475 // this is the same peer reconnecting, but the original state was
476 // not cleaned up - XXX check liveness of original ChannelHandler
477 log.debug("{}:duplicate found", getPeerInfoString());
Jonathan Hart51539b82015-10-29 09:53:04 -0700478 duplicateBgpIdFound = Boolean.FALSE;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530479 }
480
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530481 stopKeepAliveTimer();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530482 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530483 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530484 log.warn("No bgp ip in channelHandler registered for " + "disconnected peer {}", getPeerInfoString());
485 }
486 }
487
488 @Override
489 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
490
491 log.info("[exceptionCaught]: " + e.toString());
492
493 if (e.getCause() instanceof ReadTimeoutException) {
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530494 // device timeout
495 log.error("Disconnecting device {} due to read timeout", getPeerInfoString());
496 sendNotification(BgpErrorType.HOLD_TIMER_EXPIRED, (byte) 0, null);
497 state = ChannelState.IDLE;
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530498 stopKeepAliveTimer();
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530499 ctx.getChannel().close();
500 return;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530501 } else if (e.getCause() instanceof ClosedChannelException) {
502 log.debug("Channel for bgp {} already closed", getPeerInfoString());
503 } else if (e.getCause() instanceof IOException) {
504 log.error("Disconnecting peer {} due to IO Error: {}", getPeerInfoString(), e.getCause().getMessage());
505 if (log.isDebugEnabled()) {
506 // still print stack trace if debug is enabled
507 log.debug("StackTrace for previous Exception: ", e.getCause());
508 }
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530509 stopKeepAliveTimer();
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530510 ctx.getChannel().close();
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530511 } else if (e.getCause() instanceof BgpParseException) {
Shashikanth VHdae80402015-11-20 14:20:33 +0530512 byte[] data = new byte[] {};
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530513 BgpParseException errMsg = (BgpParseException) e.getCause();
Shashikanth VHdae80402015-11-20 14:20:33 +0530514 byte errorCode = errMsg.getErrorCode();
515 byte errorSubCode = errMsg.getErrorSubCode();
516 ChannelBuffer tempCb = errMsg.getData();
517 if (tempCb != null) {
518 int dataLength = tempCb.capacity();
519 data = new byte[dataLength];
520 tempCb.readBytes(data, 0, dataLength);
521 }
522 sendNotification(errorCode, errorSubCode, data);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530523 } else if (e.getCause() instanceof RejectedExecutionException) {
524 log.warn("Could not process message: queue full");
525 } else {
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530526 stopKeepAliveTimer();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530527 log.error("Error while processing message from peer " + getPeerInfoString() + "state " + this.state);
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530528 ctx.getChannel().close();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530529 }
530 }
531
532 @Override
533 public String toString() {
534 return getPeerInfoString();
535 }
536
537 @Override
538 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
539 if (e.getMessage() instanceof List) {
540 @SuppressWarnings("Unchecked")
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530541 List<BgpMessage> msglist = (List<BgpMessage>) e.getMessage();
542 for (BgpMessage pm : msglist) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530543 // Do the actual packet processing
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530544 state.processBgpMessage(this, pm);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530545 }
546 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530547 state.processBgpMessage(this, (BgpMessage) e.getMessage());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530548 }
549 }
550
Shashikanth VH447c6b02015-11-25 21:25:35 +0530551 /**
552 * Check for connection collision.
553 *
554 * @param state connection state
555 * @param peerIdentifier BGP peer identifier
556 * @param peerAddr BGP peer address
557 * @return true if bgp spreakers initiated connection
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530558 * @throws BgpParseException on error while procession collision detection
Shashikanth VH447c6b02015-11-25 21:25:35 +0530559 * @throws IOException on error while procession collision detection
560 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530561 public boolean connectionCollisionDetection(BgpPeerCfg.State state, int peerIdentifier, String peerAddr)
562 throws IOException, BgpParseException {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530563 /*
564 * RFC 4271, Section 6.8, Based on the value of the BGP identifier, a convention is established for detecting
565 * which BGP connection is to be preserved when a collision occurs. The convention is to compare the BGP
566 * Identifiers of the peers involved in the collision and to retain only the connection initiated by the BGP
567 * speaker with the higher-valued BGP Identifier..
568 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530569 BgpPeerCfg.State currentState = bgpconfig.getPeerConnState(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530570 if (currentState.equals(state)) {
571 if (((Ip4Address.valueOf(bgpconfig.getRouterId())).compareTo(Ip4Address.valueOf(peerIdentifier))) > 0) {
572 // send notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530573 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_COLLISION_RESOLUTION, null);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530574 log.debug("Connection collision detected, local id: {}, peer id: {}, peer state:{}, in state:{}",
575 (Ip4Address.valueOf(bgpconfig.getRouterId())), (Ip4Address.valueOf(peerIdentifier)),
576 currentState, state);
577 return true;
578 }
579 }
580
581 return false;
582 }
583
Shashikanth VH6de20d32015-10-09 12:04:13 +0530584 // *************************
585 // Channel utility methods
586 // *************************
587 /**
588 * Set handshake status.
589 *
590 * @param handshakeComplete handshake complete status
591 */
592 public void setHandshakeComplete(boolean handshakeComplete) {
593 this.state.setHandshakeComplete(handshakeComplete);
594 }
595
596 /**
597 * Is this a state in which the handshake has completed?
598 *
599 * @return true if the handshake is complete
600 */
601 public boolean isHandshakeComplete() {
602 return state.isHandshakeComplete();
603 }
604
605 /**
606 * To handle the BGP message.
607 *
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530608 * @param m bgp message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530609 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530610 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530611 private void dispatchMessage(BgpMessage m) throws BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530612 bgpPacketStats.addInPacket();
Jonathan Hart51539b82015-10-29 09:53:04 -0700613 bgpController.processBgpPacket(thisbgpId, m);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530614 }
615
616 /**
617 * Return a string describing this peer based on the already available information (ip address and/or remote
618 * socket).
619 *
620 * @return display string
621 */
622 private String getPeerInfoString() {
623 if (bgpPeer != null) {
624 return bgpPeer.toString();
625 }
626 String channelString;
627 if (channel == null || channel.getRemoteAddress() == null) {
628 channelString = "?";
629 } else {
630 channelString = channel.getRemoteAddress().toString();
631 }
632 String bgpIpString;
633 // TODO: implement functionality to get bgp id string
634 bgpIpString = "?";
635 return String.format("[%s BGP-IP[%s]]", channelString, bgpIpString);
636 }
637
638 /**
639 * Update the channels state. Only called from the state machine. TODO: enforce restricted state transitions
640 *
641 * @param state
642 */
643 private void setState(ChannelState state) {
644 this.state = state;
645 }
646
647 /**
648 * get packet statistics.
649 *
650 * @return packet statistics
651 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530652 public BgpPacketStatsImpl getBgpPacketStats() {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530653 return bgpPacketStats;
654 }
655
656 /**
657 * Send handshake open message to the peer.
658 *
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530659 * @throws IOException, BgpParseException
Shashikanth VH6de20d32015-10-09 12:04:13 +0530660 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530661 private void sendHandshakeOpenMessage() throws IOException, BgpParseException {
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530662 int bgpId;
663
Shashikanth VH97e571e2016-01-05 12:15:14 +0530664 bgpId = Ip4Address.valueOf(bgpconfig.getRouterId()).toInt();
665 BgpMessage msg = factory4.openMessageBuilder().setAsNumber((short) bgpconfig.getAsNumber())
Shashikanth VH447c6b02015-11-25 21:25:35 +0530666 .setHoldTime(bgpconfig.getHoldTime()).setBgpId(bgpId).setLsCapabilityTlv(bgpconfig.getLsCapability())
667 .setLargeAsCapabilityTlv(bgpconfig.getLargeASCapability()).build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530668 log.debug("Sending open message to {}", channel.getRemoteAddress());
669 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530670
671 }
672
673 /**
Shashikanth VHdae80402015-11-20 14:20:33 +0530674 * Send notification message to peer.
675 *
676 * @param errorCode error code send in notification
677 * @param errorSubCode sub error code send in notification
678 * @param data data to send in notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530679 * @throws IOException, BgpParseException while building message
Shashikanth VHdae80402015-11-20 14:20:33 +0530680 */
681 private void sendNotification(byte errorCode, byte errorSubCode, byte[] data)
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530682 throws IOException, BgpParseException {
683 BgpMessage msg = factory4.notificationMessageBuilder().setErrorCode(errorCode)
Shashikanth VH447c6b02015-11-25 21:25:35 +0530684 .setErrorSubCode(errorSubCode).setData(data).build();
Shashikanth VHdae80402015-11-20 14:20:33 +0530685 log.debug("Sending notification message to {}", channel.getRemoteAddress());
686 channel.write(Collections.singletonList(msg));
687 }
688
689 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530690 * Send keep alive message.
691 *
692 * @throws IOException when channel is disconnected
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530693 * @throws BgpParseException while building keep alive message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530694 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530695 synchronized void sendKeepAliveMessage() throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530696
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530697 BgpMessage msg = factory4.keepaliveMessageBuilder().build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530698 log.debug("Sending keepalive message to {}", channel.getRemoteAddress());
699 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530700 }
701
702 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530703 * Process unknown BGP message received.
704 *
Shashikanth VHdae80402015-11-20 14:20:33 +0530705 * @param errorCode error code
706 * @param errorSubCode error sub code
707 * @param data message type
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530708 * @throws BgpParseException while processing error messsage
Shashikanth VHdae80402015-11-20 14:20:33 +0530709 * @throws IOException while processing error message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530710 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530711 public void processUnknownMsg(byte errorCode, byte errorSubCode, byte data) throws BgpParseException, IOException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530712 log.debug("UNKNOWN message received");
Shashikanth VHdae80402015-11-20 14:20:33 +0530713 byte[] byteArray = new byte[1];
714 byteArray[0] = data;
715 sendNotification(errorCode, errorSubCode, byteArray);
716 channel.close();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530717 }
718
719 /**
Vidyashree Ramaee293252015-11-18 17:00:11 +0530720 * BGP open message validation.
Shashikanth VH6de20d32015-10-09 12:04:13 +0530721 *
722 * @param h channel handler
Vidyashree Ramaee293252015-11-18 17:00:11 +0530723 * @param openMsg open message
724 * @return true if valid message, otherwise false
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530725 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530726 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530727 public boolean openMsgValidation(BgpChannelHandler h, BgpOpenMsg openMsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530728 boolean result;
729
730 // Validate BGP ID
731 result = bgpIdValidation(openMsg);
732 if (!result) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530733 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_BGP_IDENTIFIER, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530734 }
735
Shashikanth VH97e571e2016-01-05 12:15:14 +0530736 // Validate AS number
737 result = asNumberValidation(h, openMsg);
738 if (!result) {
739 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
740 }
Vidyashree Ramaee293252015-11-18 17:00:11 +0530741
742 // Validate hold timer
743 if ((openMsg.getHoldTime() != 0) && (openMsg.getHoldTime() < BGP_MIN_HOLDTIME)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530744 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNACCEPTABLE_HOLD_TIME, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530745 }
746
747 // Validate capabilities
748 result = capabilityValidation(h, openMsg);
749 return result;
750 }
751
752 /**
753 * Capability Validation.
754 *
755 * @param h channel handler
756 * @param openmsg open message
757 * @return success or failure
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530758 * @throws BgpParseException
Vidyashree Ramaee293252015-11-18 17:00:11 +0530759 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530760 private boolean capabilityValidation(BgpChannelHandler h, BgpOpenMsg openmsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530761 log.debug("capabilityValidation");
762
763 boolean isMultiProtocolcapabilityExists = false;
764 boolean isFourOctetCapabilityExits = false;
765 int capAsNum = 0;
766
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530767 List<BgpValueType> capabilityTlv = openmsg.getCapabilityTlv();
768 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
769 List<BgpValueType> unSupportedCapabilityTlv = new LinkedList<>();
770 ListIterator<BgpValueType> unSupportedCaplistIterator = unSupportedCapabilityTlv.listIterator();
771 BgpValueType tempTlv;
Vidyashree Ramaee293252015-11-18 17:00:11 +0530772 boolean isLargeAsCapabilityCfg = h.bgpconfig.getLargeASCapability();
773 boolean isLsCapabilityCfg = h.bgpconfig.getLsCapability();
774
775 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530776 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530777 if (tlv.getType() == MULTI_PROTOCOL_EXTN_CAPA_TYPE) {
778 isMultiProtocolcapabilityExists = true;
779 }
780 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
781 isFourOctetCapabilityExits = true;
782 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
783 }
784 }
785
786 if (isFourOctetCapabilityExits) {
787 if (capAsNum > MAX_AS2_NUM) {
788 if (openmsg.getAsNumber() != AS_TRANS) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530789 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530790 }
791 } else {
792 if (capAsNum != openmsg.getAsNumber()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530793 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530794 }
795 }
796 }
797
798 if ((isLsCapabilityCfg)) {
799 if (!isMultiProtocolcapabilityExists) {
800 tempTlv = new MultiProtocolExtnCapabilityTlv(AFI, RES, SAFI);
801 unSupportedCapabilityTlv.add(tempTlv);
802 }
803 }
804
805 if ((isLargeAsCapabilityCfg)) {
806 if (!isFourOctetCapabilityExits) {
807 tempTlv = new FourOctetAsNumCapabilityTlv(h.bgpconfig.getAsNumber());
808 unSupportedCapabilityTlv.add(tempTlv);
809 }
810 }
811
812 if (unSupportedCaplistIterator.hasNext()) {
813 ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
814 while (unSupportedCaplistIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530815 BgpValueType tlv = unSupportedCaplistIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530816 tlv.write(buffer);
817 }
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530818 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNSUPPORTED_CAPABILITY, buffer);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530819 } else {
820 return true;
821 }
822 }
823
824 /**
825 * AS Number Validation.
826 *
827 * @param h channel Handler
828 * @param openMsg open message
829 * @return true or false
830 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530831 private boolean asNumberValidation(BgpChannelHandler h, BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530832 log.debug("AS Num validation");
833
834 int capAsNum = 0;
835 boolean isFourOctetCapabilityExits = false;
836
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530837 BgpPeerCfg peerCfg = h.bgpconfig.displayPeers(peerAddr);
838 List<BgpValueType> capabilityTlv = openMsg.getCapabilityTlv();
839 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530840
841 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530842 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530843 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
844 isFourOctetCapabilityExits = true;
845 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
846 }
847 }
848
849 if (peerCfg.getAsNumber() > MAX_AS2_NUM) {
850 if (openMsg.getAsNumber() != AS_TRANS) {
851 return false;
852 }
853
854 if (!isFourOctetCapabilityExits) {
855 return false;
856 }
857
858 if (peerCfg.getAsNumber() != capAsNum) {
859 return false;
860 }
861
862 isIbgpSession = peerCfg.getIsIBgp();
863 if (isIbgpSession) {
864 // IBGP - AS number should be same for Peer and local if it is IBGP
865 if (h.bgpconfig.getAsNumber() != capAsNum) {
866 return false;
867 }
868 }
869 } else {
870
871 if (openMsg.getAsNumber() != peerCfg.getAsNumber()) {
872 return false;
873 }
874
875 if (isFourOctetCapabilityExits) {
876 if (capAsNum != peerCfg.getAsNumber()) {
877 return false;
878 }
879 }
880
881 isIbgpSession = peerCfg.getIsIBgp();
882 if (isIbgpSession) {
883 // IBGP - AS number should be same for Peer and local if it is IBGP
884 if (openMsg.getAsNumber() != h.bgpconfig.getAsNumber()) {
885 return false;
886 }
887 }
888 }
889 return true;
890 }
891
892 /**
893 * Validates BGP ID.
894 *
895 * @param openMsg open message
896 * @return true or false
897 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530898 private boolean bgpIdValidation(BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530899 String openMsgBgpId = Ip4Address.valueOf(openMsg.getBgpId()).toString();
900
901 InetAddress ipAddress;
902 try {
903 ipAddress = InetAddress.getByName(openMsgBgpId);
904 if (ipAddress.isMulticastAddress()) {
905 return false;
906 }
907 } catch (UnknownHostException e) {
908 log.debug("InetAddress convertion failed");
909 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530910 return true;
911 }
912}