blob: 45be255e03c792a8a229616dff6feb9362c53777 [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
379 // Connection should establish only if local ip and Autonomous system number is configured.
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530380 if (bgpconfig.getState() != BgpCfg.State.IP_AS_CONFIGURED) {
381 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_REJECTED, null);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530382 channel.close();
383 log.info("BGP local AS and router ID not configured");
384 return;
385 }
386
387 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530388 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530389
390 // if peer is not configured disconnect session
391 if (!bgpconfig.isPeerConfigured(peerAddr)) {
392 log.debug("Peer is not configured {}", peerAddr);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530393 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_REJECTED, null);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530394 channel.close();
395 return;
396 }
397
398 // if connection is already established close channel
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530399 if (peerManager.isPeerConnected(BgpId.bgpId(IpAddress.valueOf(peerAddr)))) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530400 log.debug("Duplicate connection received, peer {}", peerAddr);
401 channel.close();
402 return;
403 }
404
405 if (null != channel.getPipeline().get("PassiveHandler")) {
406 log.info("BGP handle connection request from peer");
407 // Wait for open message from bgp peer
408 setState(ChannelState.OPENWAIT);
409 } else if (null != channel.getPipeline().get("ActiveHandler")) {
410 log.info("BGP handle connection response from peer");
411
412 sendHandshakeOpenMessage();
413 bgpPacketStats.addOutPacket();
414 setState(ChannelState.OPENSENT);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530415 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.OPENSENT);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530416 }
417 }
418
419 @Override
420 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
421
422 channel = e.getChannel();
423 log.info("BGP disconnected callback for bgp:{}. Cleaning up ...", getPeerInfoString());
424
425 address = channel.getRemoteAddress();
426 if (!(address instanceof InetSocketAddress)) {
427 throw new IOException("Invalid peer connection.");
428 }
429
430 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530431 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530432
433 if (thisbgpId != null) {
434 if (!duplicateBGPIdFound) {
435 // if the disconnected peer (on this ChannelHandler)
436 // was not one with a duplicate, it is safe to remove all
437 // state for it at the controller. Notice that if the disconnected
438 // peer was a duplicate-ip, calling the method below would clear
439 // all state for the original peer (with the same ip),
440 // which we obviously don't want.
441 log.debug("{}:removal called", getPeerInfoString());
442 if (bgpPeer != null) {
Shashikanth VH3fe37982015-11-30 11:50:07 +0530443 BgpPeerImpl peer = (BgpPeerImpl) bgpPeer;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530444 peerManager.removeConnectedPeer(thisbgpId);
Shashikanth VH3fe37982015-11-30 11:50:07 +0530445 peer.updateLocalRIBOnPeerDisconnect();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530446 }
Shashikanth VH447c6b02015-11-25 21:25:35 +0530447
448 // Retry connection if connection is lost to bgp speaker/peer
449 if ((channel != null) && (null != channel.getPipeline().get("ActiveHandler"))) {
450 BgpConnectPeerImpl connectPeer;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530451 BgpPeerCfg.State peerCfgState;
Shashikanth VH447c6b02015-11-25 21:25:35 +0530452
453 peerCfgState = bgpconfig.getPeerConnState(peerAddr);
454 // on session disconnect using configuration, do not retry
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530455 if (!peerCfgState.equals(BgpPeerCfg.State.IDLE)) {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530456 log.debug("Connection reset by peer, retry, STATE:{}", peerCfgState);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530457 BgpPeerConfig peerConfig = (BgpPeerConfig) bgpconfig.displayPeers(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530458
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530459 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530460 connectPeer = new BgpConnectPeerImpl(bgpController, peerAddr, Controller.getBgpPortNum());
461 peerConfig.setConnectPeer(connectPeer);
462 }
463 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530464 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530465 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530466 } else {
467 // A duplicate was disconnected on this ChannelHandler,
468 // this is the same peer reconnecting, but the original state was
469 // not cleaned up - XXX check liveness of original ChannelHandler
470 log.debug("{}:duplicate found", getPeerInfoString());
471 duplicateBGPIdFound = Boolean.FALSE;
472 }
473
474 if (null != keepAliveTimer) {
475 keepAliveTimer.getKeepAliveTimer().cancel();
476 }
477 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530478 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530479 log.warn("No bgp ip in channelHandler registered for " + "disconnected peer {}", getPeerInfoString());
480 }
481 }
482
483 @Override
484 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
485
486 log.info("[exceptionCaught]: " + e.toString());
487
488 if (e.getCause() instanceof ReadTimeoutException) {
489 if ((ChannelState.OPENWAIT == state) || (ChannelState.OPENSENT == state)) {
490
491 // When ReadTimeout timer is expired in OPENWAIT/OPENSENT state, it is considered
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530492 sendNotification(BgpErrorType.HOLD_TIMER_EXPIRED, (byte) 0, null);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530493 channel.close();
494 state = ChannelState.IDLE;
495 return;
496 } else if (ChannelState.OPENCONFIRM == state) {
497
498 // When ReadTimeout timer is expired in OPENCONFIRM state.
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530499 sendNotification(BgpErrorType.HOLD_TIMER_EXPIRED, (byte) 0, null);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530500 channel.close();
501 state = ChannelState.IDLE;
502 return;
503 }
504 } else if (e.getCause() instanceof ClosedChannelException) {
505 log.debug("Channel for bgp {} already closed", getPeerInfoString());
506 } else if (e.getCause() instanceof IOException) {
507 log.error("Disconnecting peer {} due to IO Error: {}", getPeerInfoString(), e.getCause().getMessage());
508 if (log.isDebugEnabled()) {
509 // still print stack trace if debug is enabled
510 log.debug("StackTrace for previous Exception: ", e.getCause());
511 }
512 channel.close();
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530513 } else if (e.getCause() instanceof BgpParseException) {
Shashikanth VHdae80402015-11-20 14:20:33 +0530514 byte[] data = new byte[] {};
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530515 BgpParseException errMsg = (BgpParseException) e.getCause();
Shashikanth VHdae80402015-11-20 14:20:33 +0530516 byte errorCode = errMsg.getErrorCode();
517 byte errorSubCode = errMsg.getErrorSubCode();
518 ChannelBuffer tempCb = errMsg.getData();
519 if (tempCb != null) {
520 int dataLength = tempCb.capacity();
521 data = new byte[dataLength];
522 tempCb.readBytes(data, 0, dataLength);
523 }
524 sendNotification(errorCode, errorSubCode, data);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530525 } else if (e.getCause() instanceof RejectedExecutionException) {
526 log.warn("Could not process message: queue full");
527 } else {
528 log.error("Error while processing message from peer " + getPeerInfoString() + "state " + this.state);
529 channel.close();
530 }
531 }
532
533 @Override
534 public String toString() {
535 return getPeerInfoString();
536 }
537
538 @Override
539 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
540 if (e.getMessage() instanceof List) {
541 @SuppressWarnings("Unchecked")
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530542 List<BgpMessage> msglist = (List<BgpMessage>) e.getMessage();
543 for (BgpMessage pm : msglist) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530544 // Do the actual packet processing
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530545 state.processBgpMessage(this, pm);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530546 }
547 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530548 state.processBgpMessage(this, (BgpMessage) e.getMessage());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530549 }
550 }
551
Shashikanth VH447c6b02015-11-25 21:25:35 +0530552 /**
553 * Check for connection collision.
554 *
555 * @param state connection state
556 * @param peerIdentifier BGP peer identifier
557 * @param peerAddr BGP peer address
558 * @return true if bgp spreakers initiated connection
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530559 * @throws BgpParseException on error while procession collision detection
Shashikanth VH447c6b02015-11-25 21:25:35 +0530560 * @throws IOException on error while procession collision detection
561 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530562 public boolean connectionCollisionDetection(BgpPeerCfg.State state, int peerIdentifier, String peerAddr)
563 throws IOException, BgpParseException {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530564 /*
565 * RFC 4271, Section 6.8, Based on the value of the BGP identifier, a convention is established for detecting
566 * which BGP connection is to be preserved when a collision occurs. The convention is to compare the BGP
567 * Identifiers of the peers involved in the collision and to retain only the connection initiated by the BGP
568 * speaker with the higher-valued BGP Identifier..
569 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530570 BgpPeerCfg.State currentState = bgpconfig.getPeerConnState(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530571 if (currentState.equals(state)) {
572 if (((Ip4Address.valueOf(bgpconfig.getRouterId())).compareTo(Ip4Address.valueOf(peerIdentifier))) > 0) {
573 // send notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530574 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_COLLISION_RESOLUTION, null);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530575 log.debug("Connection collision detected, local id: {}, peer id: {}, peer state:{}, in state:{}",
576 (Ip4Address.valueOf(bgpconfig.getRouterId())), (Ip4Address.valueOf(peerIdentifier)),
577 currentState, state);
578 return true;
579 }
580 }
581
582 return false;
583 }
584
Shashikanth VH6de20d32015-10-09 12:04:13 +0530585 // *************************
586 // Channel utility methods
587 // *************************
588 /**
589 * Set handshake status.
590 *
591 * @param handshakeComplete handshake complete status
592 */
593 public void setHandshakeComplete(boolean handshakeComplete) {
594 this.state.setHandshakeComplete(handshakeComplete);
595 }
596
597 /**
598 * Is this a state in which the handshake has completed?
599 *
600 * @return true if the handshake is complete
601 */
602 public boolean isHandshakeComplete() {
603 return state.isHandshakeComplete();
604 }
605
606 /**
607 * To handle the BGP message.
608 *
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530609 * @param m bgp message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530610 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530611 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530612 private void dispatchMessage(BgpMessage m) throws BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530613 bgpPacketStats.addInPacket();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530614 bgpController.processBGPPacket(thisbgpId, m);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530615 }
616
617 /**
618 * Return a string describing this peer based on the already available information (ip address and/or remote
619 * socket).
620 *
621 * @return display string
622 */
623 private String getPeerInfoString() {
624 if (bgpPeer != null) {
625 return bgpPeer.toString();
626 }
627 String channelString;
628 if (channel == null || channel.getRemoteAddress() == null) {
629 channelString = "?";
630 } else {
631 channelString = channel.getRemoteAddress().toString();
632 }
633 String bgpIpString;
634 // TODO: implement functionality to get bgp id string
635 bgpIpString = "?";
636 return String.format("[%s BGP-IP[%s]]", channelString, bgpIpString);
637 }
638
639 /**
640 * Update the channels state. Only called from the state machine. TODO: enforce restricted state transitions
641 *
642 * @param state
643 */
644 private void setState(ChannelState state) {
645 this.state = state;
646 }
647
648 /**
649 * get packet statistics.
650 *
651 * @return packet statistics
652 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530653 public BgpPacketStatsImpl getBgpPacketStats() {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530654 return bgpPacketStats;
655 }
656
657 /**
658 * Send handshake open message to the peer.
659 *
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530660 * @throws IOException, BgpParseException
Shashikanth VH6de20d32015-10-09 12:04:13 +0530661 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530662 private void sendHandshakeOpenMessage() throws IOException, BgpParseException {
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530663 int bgpId;
664
665 bgpId = Ip4Address.valueOf(bgpconfig.getRouterId()).toInt();
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530666 BgpMessage msg = factory4.openMessageBuilder().setAsNumber((short) bgpconfig.getAsNumber())
Shashikanth VH447c6b02015-11-25 21:25:35 +0530667 .setHoldTime(bgpconfig.getHoldTime()).setBgpId(bgpId).setLsCapabilityTlv(bgpconfig.getLsCapability())
668 .setLargeAsCapabilityTlv(bgpconfig.getLargeASCapability()).build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530669 log.debug("Sending open message to {}", channel.getRemoteAddress());
670 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530671
672 }
673
674 /**
Shashikanth VHdae80402015-11-20 14:20:33 +0530675 * Send notification message to peer.
676 *
677 * @param errorCode error code send in notification
678 * @param errorSubCode sub error code send in notification
679 * @param data data to send in notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530680 * @throws IOException, BgpParseException while building message
Shashikanth VHdae80402015-11-20 14:20:33 +0530681 */
682 private void sendNotification(byte errorCode, byte errorSubCode, byte[] data)
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530683 throws IOException, BgpParseException {
684 BgpMessage msg = factory4.notificationMessageBuilder().setErrorCode(errorCode)
Shashikanth VH447c6b02015-11-25 21:25:35 +0530685 .setErrorSubCode(errorSubCode).setData(data).build();
Shashikanth VHdae80402015-11-20 14:20:33 +0530686 log.debug("Sending notification message to {}", channel.getRemoteAddress());
687 channel.write(Collections.singletonList(msg));
688 }
689
690 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530691 * Send keep alive message.
692 *
693 * @throws IOException when channel is disconnected
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530694 * @throws BgpParseException while building keep alive message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530695 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530696 synchronized void sendKeepAliveMessage() throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530697
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530698 BgpMessage msg = factory4.keepaliveMessageBuilder().build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530699 log.debug("Sending keepalive message to {}", channel.getRemoteAddress());
700 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530701 }
702
703 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530704 * Process unknown BGP message received.
705 *
Shashikanth VHdae80402015-11-20 14:20:33 +0530706 * @param errorCode error code
707 * @param errorSubCode error sub code
708 * @param data message type
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530709 * @throws BgpParseException while processing error messsage
Shashikanth VHdae80402015-11-20 14:20:33 +0530710 * @throws IOException while processing error message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530711 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530712 public void processUnknownMsg(byte errorCode, byte errorSubCode, byte data) throws BgpParseException, IOException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530713 log.debug("UNKNOWN message received");
Shashikanth VHdae80402015-11-20 14:20:33 +0530714 byte[] byteArray = new byte[1];
715 byteArray[0] = data;
716 sendNotification(errorCode, errorSubCode, byteArray);
717 channel.close();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530718 }
719
720 /**
Vidyashree Ramaee293252015-11-18 17:00:11 +0530721 * BGP open message validation.
Shashikanth VH6de20d32015-10-09 12:04:13 +0530722 *
723 * @param h channel handler
Vidyashree Ramaee293252015-11-18 17:00:11 +0530724 * @param openMsg open message
725 * @return true if valid message, otherwise false
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530726 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530727 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530728 public boolean openMsgValidation(BgpChannelHandler h, BgpOpenMsg openMsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530729 boolean result;
730
731 // Validate BGP ID
732 result = bgpIdValidation(openMsg);
733 if (!result) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530734 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_BGP_IDENTIFIER, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530735 }
736
737 // Validate AS number
738 result = asNumberValidation(h, openMsg);
739 if (!result) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530740 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530741 }
742
743 // Validate hold timer
744 if ((openMsg.getHoldTime() != 0) && (openMsg.getHoldTime() < BGP_MIN_HOLDTIME)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530745 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNACCEPTABLE_HOLD_TIME, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530746 }
747
748 // Validate capabilities
749 result = capabilityValidation(h, openMsg);
750 return result;
751 }
752
753 /**
754 * Capability Validation.
755 *
756 * @param h channel handler
757 * @param openmsg open message
758 * @return success or failure
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530759 * @throws BgpParseException
Vidyashree Ramaee293252015-11-18 17:00:11 +0530760 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530761 private boolean capabilityValidation(BgpChannelHandler h, BgpOpenMsg openmsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530762 log.debug("capabilityValidation");
763
764 boolean isMultiProtocolcapabilityExists = false;
765 boolean isFourOctetCapabilityExits = false;
766 int capAsNum = 0;
767
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530768 List<BgpValueType> capabilityTlv = openmsg.getCapabilityTlv();
769 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
770 List<BgpValueType> unSupportedCapabilityTlv = new LinkedList<>();
771 ListIterator<BgpValueType> unSupportedCaplistIterator = unSupportedCapabilityTlv.listIterator();
772 BgpValueType tempTlv;
Vidyashree Ramaee293252015-11-18 17:00:11 +0530773 boolean isLargeAsCapabilityCfg = h.bgpconfig.getLargeASCapability();
774 boolean isLsCapabilityCfg = h.bgpconfig.getLsCapability();
775
776 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530777 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530778 if (tlv.getType() == MULTI_PROTOCOL_EXTN_CAPA_TYPE) {
779 isMultiProtocolcapabilityExists = true;
780 }
781 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
782 isFourOctetCapabilityExits = true;
783 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
784 }
785 }
786
787 if (isFourOctetCapabilityExits) {
788 if (capAsNum > MAX_AS2_NUM) {
789 if (openmsg.getAsNumber() != AS_TRANS) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530790 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530791 }
792 } else {
793 if (capAsNum != openmsg.getAsNumber()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530794 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530795 }
796 }
797 }
798
799 if ((isLsCapabilityCfg)) {
800 if (!isMultiProtocolcapabilityExists) {
801 tempTlv = new MultiProtocolExtnCapabilityTlv(AFI, RES, SAFI);
802 unSupportedCapabilityTlv.add(tempTlv);
803 }
804 }
805
806 if ((isLargeAsCapabilityCfg)) {
807 if (!isFourOctetCapabilityExits) {
808 tempTlv = new FourOctetAsNumCapabilityTlv(h.bgpconfig.getAsNumber());
809 unSupportedCapabilityTlv.add(tempTlv);
810 }
811 }
812
813 if (unSupportedCaplistIterator.hasNext()) {
814 ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
815 while (unSupportedCaplistIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530816 BgpValueType tlv = unSupportedCaplistIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530817 tlv.write(buffer);
818 }
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530819 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNSUPPORTED_CAPABILITY, buffer);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530820 } else {
821 return true;
822 }
823 }
824
825 /**
826 * AS Number Validation.
827 *
828 * @param h channel Handler
829 * @param openMsg open message
830 * @return true or false
831 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530832 private boolean asNumberValidation(BgpChannelHandler h, BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530833 log.debug("AS Num validation");
834
835 int capAsNum = 0;
836 boolean isFourOctetCapabilityExits = false;
837
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530838 BgpPeerCfg peerCfg = h.bgpconfig.displayPeers(peerAddr);
839 List<BgpValueType> capabilityTlv = openMsg.getCapabilityTlv();
840 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530841
842 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530843 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530844 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
845 isFourOctetCapabilityExits = true;
846 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
847 }
848 }
849
850 if (peerCfg.getAsNumber() > MAX_AS2_NUM) {
851 if (openMsg.getAsNumber() != AS_TRANS) {
852 return false;
853 }
854
855 if (!isFourOctetCapabilityExits) {
856 return false;
857 }
858
859 if (peerCfg.getAsNumber() != capAsNum) {
860 return false;
861 }
862
863 isIbgpSession = peerCfg.getIsIBgp();
864 if (isIbgpSession) {
865 // IBGP - AS number should be same for Peer and local if it is IBGP
866 if (h.bgpconfig.getAsNumber() != capAsNum) {
867 return false;
868 }
869 }
870 } else {
871
872 if (openMsg.getAsNumber() != peerCfg.getAsNumber()) {
873 return false;
874 }
875
876 if (isFourOctetCapabilityExits) {
877 if (capAsNum != peerCfg.getAsNumber()) {
878 return false;
879 }
880 }
881
882 isIbgpSession = peerCfg.getIsIBgp();
883 if (isIbgpSession) {
884 // IBGP - AS number should be same for Peer and local if it is IBGP
885 if (openMsg.getAsNumber() != h.bgpconfig.getAsNumber()) {
886 return false;
887 }
888 }
889 }
890 return true;
891 }
892
893 /**
894 * Validates BGP ID.
895 *
896 * @param openMsg open message
897 * @return true or false
898 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530899 private boolean bgpIdValidation(BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530900 String openMsgBgpId = Ip4Address.valueOf(openMsg.getBgpId()).toString();
901
902 InetAddress ipAddress;
903 try {
904 ipAddress = InetAddress.getByName(openMsgBgpId);
905 if (ipAddress.isMulticastAddress()) {
906 return false;
907 }
908 } catch (UnknownHostException e) {
909 log.debug("InetAddress convertion failed");
910 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530911 return true;
912 }
913}