blob: 7f4f59a74393ee64373234d2885f3a36dc5b4948 [file] [log] [blame]
Satish Ke107e662015-09-21 19:00:17 +05301/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Satish Ke107e662015-09-21 19:00:17 +05303 *
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 VH0a82a8e2016-02-02 20:42:53 +053047import org.onosproject.bgpio.util.Constants;
Shashikanth VH6de20d32015-10-09 12:04:13 +053048import org.slf4j.Logger;
49import org.slf4j.LoggerFactory;
Satish Ke107e662015-09-21 19:00:17 +053050
Jonathan Hart51539b82015-10-29 09:53:04 -070051import java.io.IOException;
52import java.net.InetAddress;
53import java.net.InetSocketAddress;
54import java.net.SocketAddress;
55import java.net.UnknownHostException;
56import java.nio.channels.ClosedChannelException;
57import java.util.Collections;
58import java.util.LinkedList;
59import java.util.List;
60import java.util.ListIterator;
61import java.util.concurrent.RejectedExecutionException;
62
Satish Ke107e662015-09-21 19:00:17 +053063/**
64 * Channel handler deals with the bgp peer connection and dispatches messages from peer to the appropriate locations.
65 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053066class BgpChannelHandler extends IdleStateAwareChannelHandler {
Satish Ke107e662015-09-21 19:00:17 +053067
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053068 private static final Logger log = LoggerFactory.getLogger(BgpChannelHandler.class);
Vidyashree Ramaee293252015-11-18 17:00:11 +053069 static final int BGP_MIN_HOLDTIME = 3;
Shashikanth VH6de20d32015-10-09 12:04:13 +053070 static final int BGP_MAX_KEEPALIVE_INTERVAL = 3;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053071 private BgpPeer bgpPeer;
72 private BgpId thisbgpId;
Shashikanth VH9f8afb42015-11-04 18:00:30 +053073 private Channel channel;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053074 private BgpKeepAliveTimer keepAliveTimer = null;
Shashikanth VH6de20d32015-10-09 12:04:13 +053075 private short peerHoldTime = 0;
76 private short negotiatedHoldTime = 0;
Shashikanth VH9f8afb42015-11-04 18:00:30 +053077 private long peerAsNum;
Shashikanth VH6de20d32015-10-09 12:04:13 +053078 private int peerIdentifier;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +053079 private BgpPacketStatsImpl bgpPacketStats;
Shashikanth VH6de20d32015-10-09 12:04:13 +053080 static final int MAX_WRONG_COUNT_PACKET = 5;
Vidyashree Ramaee293252015-11-18 17:00:11 +053081 static final byte MULTI_PROTOCOL_EXTN_CAPA_TYPE = 1;
82 static final byte FOUR_OCTET_AS_NUM_CAPA_TYPE = 65;
83 static final int AS_TRANS = 23456;
84 static final int MAX_AS2_NUM = 65535;
85 static final short AFI = 16388;
86 static final byte RES = 0;
87 static final byte SAFI = 71;
Shashikanth VH6de20d32015-10-09 12:04:13 +053088
89 // State needs to be volatile because the HandshakeTimeoutHandler
90 // needs to check if the handshake is complete
91 private volatile ChannelState state;
92
93 // When a bgp peer with a ip addresss is found (i.e we already have a
94 // connected peer with the same ip), the new peer is immediately
95 // disconnected. At that point netty callsback channelDisconnected() which
Shashikanth VH9f8afb42015-11-04 18:00:30 +053096 // proceeds to cleaup peer state - we need to ensure that it does not
97 // cleanup
Shashikanth VH6de20d32015-10-09 12:04:13 +053098 // peer state for the older (still connected) peer
Jonathan Hart51539b82015-10-29 09:53:04 -070099 private volatile Boolean duplicateBgpIdFound;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530100 // Indicates the bgp version used by this bgp peer
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530101 protected BgpVersion bgpVersion;
102 private BgpController bgpController;
103 protected BgpFactory factory4;
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530104 private boolean isIbgpSession;
105 private BgpSessionInfoImpl sessionInfo;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530106 private BgpPeerManagerImpl peerManager;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530107 private InetSocketAddress inetAddress;
108 private IpAddress ipAddress;
109 private SocketAddress address;
110 private String peerAddr;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530111 private BgpCfg bgpconfig;
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530112 List<BgpValueType> remoteBgpCapability;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530113
Satish Ke107e662015-09-21 19:00:17 +0530114 /**
115 * Create a new unconnected BGPChannelHandler.
116 *
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530117 * @param bgpController bgp controller
Satish Ke107e662015-09-21 19:00:17 +0530118 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530119 BgpChannelHandler(BgpController bgpController) {
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530120 this.bgpController = bgpController;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530121 this.peerManager = (BgpPeerManagerImpl) bgpController.peerManager();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530122 this.state = ChannelState.IDLE;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530123 this.factory4 = Controller.getBgpMessageFactory4();
Jonathan Hart51539b82015-10-29 09:53:04 -0700124 this.duplicateBgpIdFound = Boolean.FALSE;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530125 this.bgpPacketStats = new BgpPacketStatsImpl();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530126 this.bgpconfig = bgpController.getConfig();
Satish Ke107e662015-09-21 19:00:17 +0530127 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530128
129 // To disconnect peer session.
130 public void disconnectPeer() {
131 bgpPeer.disconnectPeer();
132 }
133
134 // *************************
135 // Channel State Machine
136 // *************************
137
138 /**
139 * The state machine for handling the peer/channel state. All state transitions should happen from within the state
140 * machine (and not from other parts of the code)
141 */
142 enum ChannelState {
143 /**
144 * Initial state before channel is connected.
145 */
146 IDLE(false) {
147
148 },
149
150 OPENSENT(false) {
151 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530152 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530153 log.debug("message received in OPENSENT state");
154 // check for OPEN message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530155 if (m.getType() != BgpType.OPEN) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530156 // When the message type is not keep alive message increment the wrong packet statistics
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530157 h.processUnknownMsg(BgpErrorType.FINITE_STATE_MACHINE_ERROR,
158 BgpErrorType.RECEIVE_UNEXPECTED_MESSAGE_IN_OPENSENT_STATE,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530159 m.getType().getType());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530160 log.debug("Message is not OPEN message");
161 } else {
162 log.debug("Sending keep alive message in OPENSENT state");
163 h.bgpPacketStats.addInPacket();
164
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530165 BgpOpenMsg pOpenmsg = (BgpOpenMsg) m;
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530166 h.peerIdentifier = pOpenmsg.getBgpId();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530167
168 // validate capabilities and open msg
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530169 if (h.openMsgValidation(h, pOpenmsg)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530170 if (h.connectionCollisionDetection(BgpPeerCfg.State.OPENCONFIRM,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530171 h.peerIdentifier, h.peerAddr)) {
172 h.channel.close();
173 return;
174 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530175 log.debug("Sending handshake OPEN message");
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530176 h.remoteBgpCapability = pOpenmsg.getCapabilityTlv();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530177
178 /*
179 * RFC 4271, section 4.2: Upon receipt of an OPEN message, a BGP speaker MUST calculate the
180 * value of the Hold Timer by using the smaller of its configured Hold Time and the Hold Time
181 * received in the OPEN message
182 */
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530183 h.peerHoldTime = pOpenmsg.getHoldTime();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530184 if (h.peerHoldTime < h.bgpconfig.getHoldTime()) {
185 h.channel.getPipeline().replace("holdTime",
186 "holdTime",
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530187 new ReadTimeoutHandler(BgpPipelineFactory.TIMER,
Shashikanth VH6de20d32015-10-09 12:04:13 +0530188 h.peerHoldTime));
189 }
190
191 log.info("Hold Time : " + h.peerHoldTime);
192
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530193 // update AS number
194 h.peerAsNum = pOpenmsg.getAsNumber();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530195 }
196
197 // Send keepalive message to peer.
198 h.sendKeepAliveMessage();
199 h.bgpPacketStats.addOutPacket();
200 h.setState(OPENCONFIRM);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530201 h.bgpconfig.setPeerConnState(h.peerAddr, BgpPeerCfg.State.OPENCONFIRM);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530202 }
203 }
204 },
205
206 OPENWAIT(false) {
207 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530208 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530209 log.debug("Message received in OPEN WAIT State");
210
211 // check for open message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530212 if (m.getType() != BgpType.OPEN) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530213 // When the message type is not open message increment the wrong packet statistics
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530214 h.processUnknownMsg(BgpErrorType.FINITE_STATE_MACHINE_ERROR, BgpErrorType.UNSPECIFIED_ERROR,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530215 m.getType().getType());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530216 log.debug("Message is not OPEN message");
217 } else {
218 h.bgpPacketStats.addInPacket();
219
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530220 BgpOpenMsg pOpenmsg = (BgpOpenMsg) m;
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530221 h.peerIdentifier = pOpenmsg.getBgpId();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530222
223 // Validate open message
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530224 if (h.openMsgValidation(h, pOpenmsg)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530225 if (h.connectionCollisionDetection(BgpPeerCfg.State.OPENSENT,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530226 h.peerIdentifier, h.peerAddr)) {
227 h.channel.close();
228 return;
229 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530230 log.debug("Sending handshake OPEN message");
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530231 h.remoteBgpCapability = pOpenmsg.getCapabilityTlv();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530232
233 /*
234 * RFC 4271, section 4.2: Upon receipt of an OPEN message, a BGP speaker MUST calculate the
235 * value of the Hold Timer by using the smaller of its configured Hold Time and the Hold Time
236 * received in the OPEN message
237 */
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530238 h.peerHoldTime = pOpenmsg.getHoldTime();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530239 if (h.peerHoldTime < h.bgpconfig.getHoldTime()) {
240 h.channel.getPipeline().replace("holdTime",
241 "holdTime",
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530242 new ReadTimeoutHandler(BgpPipelineFactory.TIMER,
Shashikanth VH6de20d32015-10-09 12:04:13 +0530243 h.peerHoldTime));
244 }
245
246 log.debug("Hold Time : " + h.peerHoldTime);
247
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530248 // update AS number
249 h.peerAsNum = pOpenmsg.getAsNumber();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530250
251 h.sendHandshakeOpenMessage();
252 h.bgpPacketStats.addOutPacket();
253 h.setState(OPENCONFIRM);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530254 h.bgpconfig.setPeerConnState(h.peerAddr, BgpPeerCfg.State.OPENCONFIRM);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530255 }
256 }
257 }
258 },
259
260 OPENCONFIRM(false) {
261 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530262 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530263 log.debug("Message received in OPENCONFIRM state");
264 // check for keep alive message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530265 if (m.getType() != BgpType.KEEP_ALIVE) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530266 // When the message type is not keep alive message handle the wrong packet
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530267 h.processUnknownMsg(BgpErrorType.FINITE_STATE_MACHINE_ERROR,
268 BgpErrorType.RECEIVE_UNEXPECTED_MESSAGE_IN_OPENCONFIRM_STATE,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530269 m.getType().getType());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530270 log.debug("Message is not KEEPALIVE message");
271 } else {
272
273 // Set the peer connected status
274 h.bgpPacketStats.addInPacket();
275 log.debug("Sending keep alive message in OPENCONFIRM state");
276
277 final InetSocketAddress inetAddress = (InetSocketAddress) h.address;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530278 h.thisbgpId = BgpId.bgpId(IpAddress.valueOf(inetAddress.getAddress()));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530279
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530280 // set session parameters
281 h.negotiatedHoldTime = (h.peerHoldTime < h.bgpconfig.getHoldTime()) ? h.peerHoldTime
282 : h.bgpconfig.getHoldTime();
283 h.sessionInfo = new BgpSessionInfoImpl(h.thisbgpId, h.bgpVersion, h.peerAsNum, h.peerHoldTime,
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530284 h.peerIdentifier, h.negotiatedHoldTime, h.isIbgpSession,
285 h.remoteBgpCapability);
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530286
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530287 h.bgpPeer = h.peerManager.getBgpPeerInstance(h.bgpController, h.sessionInfo, h.bgpPacketStats);
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530288 // set the status of bgp as connected
Shashikanth VH6de20d32015-10-09 12:04:13 +0530289 h.bgpPeer.setConnected(true);
290 h.bgpPeer.setChannel(h.channel);
291
Shashikanth VH6de20d32015-10-09 12:04:13 +0530292 /*
293 * RFC 4271, When an OPEN message is received, sends a KEEPALIVE message, If the negotiated hold
294 * time value is zero, then the HoldTimer and KeepaliveTimer are not started. A reasonable maximum
295 * time between KEEPALIVE messages would be one third of the Hold Time interval.
296 */
Shashikanth VH6de20d32015-10-09 12:04:13 +0530297
298 if (h.negotiatedHoldTime != 0) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530299 h.keepAliveTimer = new BgpKeepAliveTimer(h,
Shashikanth VH447c6b02015-11-25 21:25:35 +0530300 (h.negotiatedHoldTime / BGP_MAX_KEEPALIVE_INTERVAL));
Shashikanth VHdae80402015-11-20 14:20:33 +0530301 } else {
302 h.sendKeepAliveMessage();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530303 }
304
305 h.bgpPacketStats.addOutPacket();
306
307 // set the state handshake completion.
308 h.setHandshakeComplete(true);
309
310 if (!h.peerManager.addConnectedPeer(h.thisbgpId, h.bgpPeer)) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530311 disconnectDuplicate(h);
312 } else {
313 h.setState(ESTABLISHED);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530314 h.bgpconfig.setPeerConnState(h.peerAddr, BgpPeerCfg.State.ESTABLISHED);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530315 }
316 }
317 }
318 },
319
320 ESTABLISHED(true) {
321 @Override
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530322 void processBgpMessage(BgpChannelHandler h, BgpMessage m) throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530323 log.debug("Message received in established state " + m.getType());
324 // dispatch the message
325 h.dispatchMessage(m);
326 }
327 };
328
329 private boolean handshakeComplete;
330
331 ChannelState(boolean handshakeComplete) {
332 this.handshakeComplete = handshakeComplete;
333 }
334
335 /**
336 * Is this a state in which the handshake has completed?
337 *
338 * @return true if the handshake is complete
339 */
340 public boolean isHandshakeComplete() {
341 return this.handshakeComplete;
342 }
343
344 /**
345 * Disconnect duplicate peer connection.
346 *
347 * @param h channel handler
348 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530349 protected void disconnectDuplicate(BgpChannelHandler h) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530350 log.error("Duplicated BGP IP or incompleted cleanup - " + "" + "disconnecting channel {}",
351 h.getPeerInfoString());
Jonathan Hart51539b82015-10-29 09:53:04 -0700352 h.duplicateBgpIdFound = Boolean.TRUE;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530353 h.channel.disconnect();
354 }
355
356 // set handshake completion status
357 public void setHandshakeComplete(boolean handshakeComplete) {
358 this.handshakeComplete = handshakeComplete;
359 }
360
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530361 void processBgpMessage(BgpChannelHandler bgpChannelHandler, BgpMessage pm)
362 throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530363 // TODO Auto-generated method stub
364 log.debug("BGP message stub");
365 }
366
367 }
368
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530369 //Stop keepalive timer
370 private void stopKeepAliveTimer() {
371 if ((keepAliveTimer != null) && (keepAliveTimer.getKeepAliveTimer() != null)) {
372 keepAliveTimer.getKeepAliveTimer().cancel();
373 }
374 }
375
Shashikanth VH6de20d32015-10-09 12:04:13 +0530376 // *************************
377 // Channel handler methods
378 // *************************
379
380 @Override
381 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
382
383 channel = e.getChannel();
384 log.info("BGP connected from {}", channel.getRemoteAddress());
385
386 address = channel.getRemoteAddress();
387 if (!(address instanceof InetSocketAddress)) {
388 throw new IOException("Invalid peer connection.");
389 }
390
Shashikanth VH97e571e2016-01-05 12:15:14 +0530391 // Connection should establish only if local ip and Autonomous system number is configured.
392 if (bgpconfig.getState() != BgpCfg.State.IP_AS_CONFIGURED) {
393 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_REJECTED, null);
394 channel.close();
395 log.info("BGP local AS and router ID not configured");
396 return;
397 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530398
399 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530400 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530401
Shashikanth VH97e571e2016-01-05 12:15:14 +0530402 // if peer is not configured disconnect session
403 if (!bgpconfig.isPeerConfigured(peerAddr)) {
404 log.debug("Peer is not configured {}", peerAddr);
405 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_REJECTED, null);
406 channel.close();
407 return;
408 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530409
410 // if connection is already established close channel
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530411 if (peerManager.isPeerConnected(BgpId.bgpId(IpAddress.valueOf(peerAddr)))) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530412 log.debug("Duplicate connection received, peer {}", peerAddr);
413 channel.close();
414 return;
415 }
416
417 if (null != channel.getPipeline().get("PassiveHandler")) {
418 log.info("BGP handle connection request from peer");
419 // Wait for open message from bgp peer
420 setState(ChannelState.OPENWAIT);
421 } else if (null != channel.getPipeline().get("ActiveHandler")) {
422 log.info("BGP handle connection response from peer");
423
424 sendHandshakeOpenMessage();
425 bgpPacketStats.addOutPacket();
426 setState(ChannelState.OPENSENT);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530427 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.OPENSENT);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530428 }
429 }
430
431 @Override
432 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
433
434 channel = e.getChannel();
435 log.info("BGP disconnected callback for bgp:{}. Cleaning up ...", getPeerInfoString());
436
437 address = channel.getRemoteAddress();
438 if (!(address instanceof InetSocketAddress)) {
439 throw new IOException("Invalid peer connection.");
440 }
441
442 inetAddress = (InetSocketAddress) address;
Shashikanth VHdae80402015-11-20 14:20:33 +0530443 peerAddr = IpAddress.valueOf(inetAddress.getAddress()).toString();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530444
445 if (thisbgpId != null) {
Jonathan Hart51539b82015-10-29 09:53:04 -0700446 if (!duplicateBgpIdFound) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530447 // if the disconnected peer (on this ChannelHandler)
448 // was not one with a duplicate, it is safe to remove all
449 // state for it at the controller. Notice that if the disconnected
450 // peer was a duplicate-ip, calling the method below would clear
451 // all state for the original peer (with the same ip),
452 // which we obviously don't want.
453 log.debug("{}:removal called", getPeerInfoString());
454 if (bgpPeer != null) {
Shashikanth VH3fe37982015-11-30 11:50:07 +0530455 BgpPeerImpl peer = (BgpPeerImpl) bgpPeer;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530456 peerManager.removeConnectedPeer(thisbgpId);
Jonathan Hart51539b82015-10-29 09:53:04 -0700457 peer.updateLocalRibOnPeerDisconnect();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530458 }
Shashikanth VH447c6b02015-11-25 21:25:35 +0530459
460 // Retry connection if connection is lost to bgp speaker/peer
461 if ((channel != null) && (null != channel.getPipeline().get("ActiveHandler"))) {
462 BgpConnectPeerImpl connectPeer;
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530463 BgpPeerCfg.State peerCfgState;
Shashikanth VH447c6b02015-11-25 21:25:35 +0530464
465 peerCfgState = bgpconfig.getPeerConnState(peerAddr);
466 // on session disconnect using configuration, do not retry
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530467 if (!peerCfgState.equals(BgpPeerCfg.State.IDLE)) {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530468 log.debug("Connection reset by peer, retry, STATE:{}", peerCfgState);
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530469 BgpPeerConfig peerConfig = (BgpPeerConfig) bgpconfig.displayPeers(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530470
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530471 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530472 connectPeer = new BgpConnectPeerImpl(bgpController, peerAddr, Controller.getBgpPortNum());
473 peerConfig.setConnectPeer(connectPeer);
474 }
475 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530476 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530477 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530478 } else {
479 // A duplicate was disconnected on this ChannelHandler,
480 // this is the same peer reconnecting, but the original state was
481 // not cleaned up - XXX check liveness of original ChannelHandler
482 log.debug("{}:duplicate found", getPeerInfoString());
Jonathan Hart51539b82015-10-29 09:53:04 -0700483 duplicateBgpIdFound = Boolean.FALSE;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530484 }
485
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530486 stopKeepAliveTimer();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530487 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530488 bgpconfig.setPeerConnState(peerAddr, BgpPeerCfg.State.IDLE);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530489 log.warn("No bgp ip in channelHandler registered for " + "disconnected peer {}", getPeerInfoString());
490 }
491 }
492
493 @Override
494 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
495
496 log.info("[exceptionCaught]: " + e.toString());
497
498 if (e.getCause() instanceof ReadTimeoutException) {
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530499 // device timeout
500 log.error("Disconnecting device {} due to read timeout", getPeerInfoString());
501 sendNotification(BgpErrorType.HOLD_TIMER_EXPIRED, (byte) 0, null);
502 state = ChannelState.IDLE;
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530503 stopKeepAliveTimer();
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530504 ctx.getChannel().close();
505 return;
Shashikanth VH6de20d32015-10-09 12:04:13 +0530506 } else if (e.getCause() instanceof ClosedChannelException) {
507 log.debug("Channel for bgp {} already closed", getPeerInfoString());
508 } else if (e.getCause() instanceof IOException) {
509 log.error("Disconnecting peer {} due to IO Error: {}", getPeerInfoString(), e.getCause().getMessage());
510 if (log.isDebugEnabled()) {
511 // still print stack trace if debug is enabled
512 log.debug("StackTrace for previous Exception: ", e.getCause());
513 }
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530514 stopKeepAliveTimer();
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530515 ctx.getChannel().close();
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530516 } else if (e.getCause() instanceof BgpParseException) {
Shashikanth VHdae80402015-11-20 14:20:33 +0530517 byte[] data = new byte[] {};
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530518 BgpParseException errMsg = (BgpParseException) e.getCause();
Shashikanth VHdae80402015-11-20 14:20:33 +0530519 byte errorCode = errMsg.getErrorCode();
520 byte errorSubCode = errMsg.getErrorSubCode();
521 ChannelBuffer tempCb = errMsg.getData();
522 if (tempCb != null) {
523 int dataLength = tempCb.capacity();
524 data = new byte[dataLength];
525 tempCb.readBytes(data, 0, dataLength);
526 }
527 sendNotification(errorCode, errorSubCode, data);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530528 } else if (e.getCause() instanceof RejectedExecutionException) {
529 log.warn("Could not process message: queue full");
530 } else {
Shashikanth VH3dd13cf2015-12-14 11:53:46 +0530531 stopKeepAliveTimer();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530532 log.error("Error while processing message from peer " + getPeerInfoString() + "state " + this.state);
Shashikanth VHa33f9a02015-12-05 12:22:23 +0530533 ctx.getChannel().close();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530534 }
535 }
536
537 @Override
538 public String toString() {
539 return getPeerInfoString();
540 }
541
542 @Override
543 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
544 if (e.getMessage() instanceof List) {
545 @SuppressWarnings("Unchecked")
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530546 List<BgpMessage> msglist = (List<BgpMessage>) e.getMessage();
547 for (BgpMessage pm : msglist) {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530548 // Do the actual packet processing
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530549 state.processBgpMessage(this, pm);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530550 }
551 } else {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530552 state.processBgpMessage(this, (BgpMessage) e.getMessage());
Shashikanth VH6de20d32015-10-09 12:04:13 +0530553 }
554 }
555
Shashikanth VH447c6b02015-11-25 21:25:35 +0530556 /**
557 * Check for connection collision.
558 *
559 * @param state connection state
560 * @param peerIdentifier BGP peer identifier
561 * @param peerAddr BGP peer address
562 * @return true if bgp spreakers initiated connection
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530563 * @throws BgpParseException on error while procession collision detection
Shashikanth VH447c6b02015-11-25 21:25:35 +0530564 * @throws IOException on error while procession collision detection
565 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530566 public boolean connectionCollisionDetection(BgpPeerCfg.State state, int peerIdentifier, String peerAddr)
567 throws IOException, BgpParseException {
Shashikanth VH447c6b02015-11-25 21:25:35 +0530568 /*
569 * RFC 4271, Section 6.8, Based on the value of the BGP identifier, a convention is established for detecting
570 * which BGP connection is to be preserved when a collision occurs. The convention is to compare the BGP
571 * Identifiers of the peers involved in the collision and to retain only the connection initiated by the BGP
572 * speaker with the higher-valued BGP Identifier..
573 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530574 BgpPeerCfg.State currentState = bgpconfig.getPeerConnState(peerAddr);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530575 if (currentState.equals(state)) {
576 if (((Ip4Address.valueOf(bgpconfig.getRouterId())).compareTo(Ip4Address.valueOf(peerIdentifier))) > 0) {
577 // send notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530578 sendNotification(BgpErrorType.CEASE, BgpErrorType.CONNECTION_COLLISION_RESOLUTION, null);
Shashikanth VH447c6b02015-11-25 21:25:35 +0530579 log.debug("Connection collision detected, local id: {}, peer id: {}, peer state:{}, in state:{}",
580 (Ip4Address.valueOf(bgpconfig.getRouterId())), (Ip4Address.valueOf(peerIdentifier)),
581 currentState, state);
582 return true;
583 }
584 }
585
586 return false;
587 }
588
Shashikanth VH6de20d32015-10-09 12:04:13 +0530589 // *************************
590 // Channel utility methods
591 // *************************
592 /**
593 * Set handshake status.
594 *
595 * @param handshakeComplete handshake complete status
596 */
597 public void setHandshakeComplete(boolean handshakeComplete) {
598 this.state.setHandshakeComplete(handshakeComplete);
599 }
600
601 /**
602 * Is this a state in which the handshake has completed?
603 *
604 * @return true if the handshake is complete
605 */
606 public boolean isHandshakeComplete() {
607 return state.isHandshakeComplete();
608 }
609
610 /**
611 * To handle the BGP message.
612 *
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530613 * @param m bgp message
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530614 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530615 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530616 private void dispatchMessage(BgpMessage m) throws BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530617 bgpPacketStats.addInPacket();
Jonathan Hart51539b82015-10-29 09:53:04 -0700618 bgpController.processBgpPacket(thisbgpId, m);
Shashikanth VH6de20d32015-10-09 12:04:13 +0530619 }
620
621 /**
622 * Return a string describing this peer based on the already available information (ip address and/or remote
623 * socket).
624 *
625 * @return display string
626 */
627 private String getPeerInfoString() {
628 if (bgpPeer != null) {
629 return bgpPeer.toString();
630 }
631 String channelString;
632 if (channel == null || channel.getRemoteAddress() == null) {
633 channelString = "?";
634 } else {
635 channelString = channel.getRemoteAddress().toString();
636 }
637 String bgpIpString;
638 // TODO: implement functionality to get bgp id string
639 bgpIpString = "?";
640 return String.format("[%s BGP-IP[%s]]", channelString, bgpIpString);
641 }
642
643 /**
644 * Update the channels state. Only called from the state machine. TODO: enforce restricted state transitions
645 *
646 * @param state
647 */
648 private void setState(ChannelState state) {
649 this.state = state;
650 }
651
652 /**
653 * get packet statistics.
654 *
655 * @return packet statistics
656 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530657 public BgpPacketStatsImpl getBgpPacketStats() {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530658 return bgpPacketStats;
659 }
660
661 /**
662 * Send handshake open message to the peer.
663 *
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530664 * @throws IOException, BgpParseException
Shashikanth VH6de20d32015-10-09 12:04:13 +0530665 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530666 private void sendHandshakeOpenMessage() throws IOException, BgpParseException {
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530667 int bgpId;
Shashikanth VH580bdeb2016-02-19 17:26:03 +0530668 BgpCfg.FlowSpec flowSpec = bgpconfig.flowSpecCapability();
Shashikanth VHdcfb7b52016-02-05 12:56:23 +0530669 boolean flowSpecStatus = false;
670 boolean vpnFlowSpecStatus = false;
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530671
Shashikanth VH97e571e2016-01-05 12:15:14 +0530672 bgpId = Ip4Address.valueOf(bgpconfig.getRouterId()).toInt();
Shashikanth VH580bdeb2016-02-19 17:26:03 +0530673
674 if (flowSpec == BgpCfg.FlowSpec.IPV4) {
Shashikanth VHdcfb7b52016-02-05 12:56:23 +0530675 flowSpecStatus = true;
Shashikanth VH580bdeb2016-02-19 17:26:03 +0530676 } else if (flowSpec == BgpCfg.FlowSpec.VPNV4) {
677 vpnFlowSpecStatus = true;
678 } else if (flowSpec == BgpCfg.FlowSpec.IPV4_VPNV4) {
679 flowSpecStatus = true;
Shashikanth VHdcfb7b52016-02-05 12:56:23 +0530680 vpnFlowSpecStatus = true;
681 }
682
Shashikanth VH97e571e2016-01-05 12:15:14 +0530683 BgpMessage msg = factory4.openMessageBuilder().setAsNumber((short) bgpconfig.getAsNumber())
Shashikanth VHdcfb7b52016-02-05 12:56:23 +0530684 .setHoldTime(bgpconfig.getHoldTime()).setBgpId(bgpId)
685 .setLsCapabilityTlv(bgpconfig.getLsCapability())
686 .setLargeAsCapabilityTlv(bgpconfig.getLargeASCapability())
687 .setFlowSpecCapabilityTlv(flowSpecStatus)
688 .setVpnFlowSpecCapabilityTlv(vpnFlowSpecStatus).build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530689 log.debug("Sending open message to {}", channel.getRemoteAddress());
690 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530691
692 }
693
694 /**
Shashikanth VHdae80402015-11-20 14:20:33 +0530695 * Send notification message to peer.
696 *
697 * @param errorCode error code send in notification
698 * @param errorSubCode sub error code send in notification
699 * @param data data to send in notification
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530700 * @throws IOException, BgpParseException while building message
Shashikanth VHdae80402015-11-20 14:20:33 +0530701 */
702 private void sendNotification(byte errorCode, byte errorSubCode, byte[] data)
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530703 throws IOException, BgpParseException {
704 BgpMessage msg = factory4.notificationMessageBuilder().setErrorCode(errorCode)
Shashikanth VH447c6b02015-11-25 21:25:35 +0530705 .setErrorSubCode(errorSubCode).setData(data).build();
Shashikanth VHdae80402015-11-20 14:20:33 +0530706 log.debug("Sending notification message to {}", channel.getRemoteAddress());
707 channel.write(Collections.singletonList(msg));
708 }
709
710 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530711 * Send keep alive message.
712 *
713 * @throws IOException when channel is disconnected
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530714 * @throws BgpParseException while building keep alive message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530715 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530716 synchronized void sendKeepAliveMessage() throws IOException, BgpParseException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530717
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530718 BgpMessage msg = factory4.keepaliveMessageBuilder().build();
Shashikanth VH9f8afb42015-11-04 18:00:30 +0530719 log.debug("Sending keepalive message to {}", channel.getRemoteAddress());
720 channel.write(Collections.singletonList(msg));
Shashikanth VH6de20d32015-10-09 12:04:13 +0530721 }
722
723 /**
Shashikanth VH6de20d32015-10-09 12:04:13 +0530724 * Process unknown BGP message received.
725 *
Shashikanth VHdae80402015-11-20 14:20:33 +0530726 * @param errorCode error code
727 * @param errorSubCode error sub code
728 * @param data message type
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530729 * @throws BgpParseException while processing error messsage
Shashikanth VHdae80402015-11-20 14:20:33 +0530730 * @throws IOException while processing error message
Shashikanth VH6de20d32015-10-09 12:04:13 +0530731 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530732 public void processUnknownMsg(byte errorCode, byte errorSubCode, byte data) throws BgpParseException, IOException {
Shashikanth VH6de20d32015-10-09 12:04:13 +0530733 log.debug("UNKNOWN message received");
Shashikanth VHdae80402015-11-20 14:20:33 +0530734 byte[] byteArray = new byte[1];
735 byteArray[0] = data;
736 sendNotification(errorCode, errorSubCode, byteArray);
737 channel.close();
Shashikanth VH6de20d32015-10-09 12:04:13 +0530738 }
739
740 /**
Vidyashree Ramaee293252015-11-18 17:00:11 +0530741 * BGP open message validation.
Shashikanth VH6de20d32015-10-09 12:04:13 +0530742 *
743 * @param h channel handler
Vidyashree Ramaee293252015-11-18 17:00:11 +0530744 * @param openMsg open message
745 * @return true if valid message, otherwise false
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530746 * @throws BgpParseException throw exception
Shashikanth VH6de20d32015-10-09 12:04:13 +0530747 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530748 public boolean openMsgValidation(BgpChannelHandler h, BgpOpenMsg openMsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530749 boolean result;
750
751 // Validate BGP ID
752 result = bgpIdValidation(openMsg);
753 if (!result) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530754 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_BGP_IDENTIFIER, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530755 }
756
Shashikanth VH97e571e2016-01-05 12:15:14 +0530757 // Validate AS number
758 result = asNumberValidation(h, openMsg);
759 if (!result) {
760 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
761 }
Vidyashree Ramaee293252015-11-18 17:00:11 +0530762
763 // Validate hold timer
764 if ((openMsg.getHoldTime() != 0) && (openMsg.getHoldTime() < BGP_MIN_HOLDTIME)) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530765 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNACCEPTABLE_HOLD_TIME, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530766 }
767
768 // Validate capabilities
769 result = capabilityValidation(h, openMsg);
770 return result;
771 }
772
773 /**
774 * Capability Validation.
775 *
776 * @param h channel handler
777 * @param openmsg open message
778 * @return success or failure
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530779 * @throws BgpParseException
Vidyashree Ramaee293252015-11-18 17:00:11 +0530780 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530781 private boolean capabilityValidation(BgpChannelHandler h, BgpOpenMsg openmsg) throws BgpParseException {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530782 log.debug("capabilityValidation");
783
Vidyashree Ramaee293252015-11-18 17:00:11 +0530784 boolean isFourOctetCapabilityExits = false;
785 int capAsNum = 0;
786
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530787 List<BgpValueType> capabilityTlv = openmsg.getCapabilityTlv();
788 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
789 List<BgpValueType> unSupportedCapabilityTlv = new LinkedList<>();
790 ListIterator<BgpValueType> unSupportedCaplistIterator = unSupportedCapabilityTlv.listIterator();
791 BgpValueType tempTlv;
Vidyashree Ramaee293252015-11-18 17:00:11 +0530792 boolean isLargeAsCapabilityCfg = h.bgpconfig.getLargeASCapability();
793 boolean isLsCapabilityCfg = h.bgpconfig.getLsCapability();
Shashikanth VHdcfb7b52016-02-05 12:56:23 +0530794 boolean isFlowSpecCapabilityCfg = false;
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530795 MultiProtocolExtnCapabilityTlv tempCapability;
796 boolean isMultiProtocolLsCapability = false;
797 boolean isMultiProtocolFlowSpecCapability = false;
798 boolean isMultiProtocolVpnFlowSpecCapability = false;
Shashikanth VH580bdeb2016-02-19 17:26:03 +0530799 BgpCfg.FlowSpec flowSpec = h.bgpconfig.flowSpecCapability();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530800
Shashikanth VH580bdeb2016-02-19 17:26:03 +0530801 if (flowSpec != BgpCfg.FlowSpec.NONE) {
Shashikanth VHdcfb7b52016-02-05 12:56:23 +0530802 isFlowSpecCapabilityCfg = true;
803 }
804
Vidyashree Ramaee293252015-11-18 17:00:11 +0530805 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530806 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530807 if (tlv.getType() == MULTI_PROTOCOL_EXTN_CAPA_TYPE) {
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530808 tempCapability = (MultiProtocolExtnCapabilityTlv) tlv;
809 if (Constants.SAFI_FLOWSPEC_VALUE == tempCapability.getSafi()) {
810 isMultiProtocolFlowSpecCapability = true;
811 }
812
813 if (Constants.VPN_SAFI_FLOWSPEC_VALUE == tempCapability.getSafi()) {
814 isMultiProtocolVpnFlowSpecCapability = true;
815 }
816
817 if (SAFI == tempCapability.getSafi()) {
818 isMultiProtocolLsCapability = true;
819 }
Vidyashree Ramaee293252015-11-18 17:00:11 +0530820 }
821 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
822 isFourOctetCapabilityExits = true;
823 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
824 }
825 }
826
827 if (isFourOctetCapabilityExits) {
828 if (capAsNum > MAX_AS2_NUM) {
829 if (openmsg.getAsNumber() != AS_TRANS) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530830 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530831 }
832 } else {
833 if (capAsNum != openmsg.getAsNumber()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530834 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.BAD_PEER_AS, null);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530835 }
836 }
837 }
838
839 if ((isLsCapabilityCfg)) {
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530840 if (!isMultiProtocolLsCapability) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530841 tempTlv = new MultiProtocolExtnCapabilityTlv(AFI, RES, SAFI);
842 unSupportedCapabilityTlv.add(tempTlv);
843 }
844 }
845
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530846 if ((isFlowSpecCapabilityCfg)) {
847 if (!isMultiProtocolFlowSpecCapability) {
848 tempTlv = new MultiProtocolExtnCapabilityTlv(Constants.AFI_FLOWSPEC_VALUE,
849 RES, Constants.SAFI_FLOWSPEC_VALUE);
850 unSupportedCapabilityTlv.add(tempTlv);
851 }
852
853 if (!isMultiProtocolVpnFlowSpecCapability) {
854 tempTlv = new MultiProtocolExtnCapabilityTlv(Constants.AFI_FLOWSPEC_VALUE,
855 RES, Constants.VPN_SAFI_FLOWSPEC_VALUE);
856 unSupportedCapabilityTlv.add(tempTlv);
857 }
858 }
859
Vidyashree Ramaee293252015-11-18 17:00:11 +0530860 if ((isLargeAsCapabilityCfg)) {
861 if (!isFourOctetCapabilityExits) {
862 tempTlv = new FourOctetAsNumCapabilityTlv(h.bgpconfig.getAsNumber());
863 unSupportedCapabilityTlv.add(tempTlv);
864 }
865 }
866
Shashikanth VH0a82a8e2016-02-02 20:42:53 +0530867 if (unSupportedCapabilityTlv.size() == 3) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530868 ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
869 while (unSupportedCaplistIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530870 BgpValueType tlv = unSupportedCaplistIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530871 tlv.write(buffer);
872 }
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530873 throw new BgpParseException(BgpErrorType.OPEN_MESSAGE_ERROR, BgpErrorType.UNSUPPORTED_CAPABILITY, buffer);
Vidyashree Ramaee293252015-11-18 17:00:11 +0530874 } else {
875 return true;
876 }
877 }
878
879 /**
880 * AS Number Validation.
881 *
882 * @param h channel Handler
883 * @param openMsg open message
884 * @return true or false
885 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530886 private boolean asNumberValidation(BgpChannelHandler h, BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530887 log.debug("AS Num validation");
888
889 int capAsNum = 0;
890 boolean isFourOctetCapabilityExits = false;
891
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530892 BgpPeerCfg peerCfg = h.bgpconfig.displayPeers(peerAddr);
893 List<BgpValueType> capabilityTlv = openMsg.getCapabilityTlv();
894 ListIterator<BgpValueType> listIterator = capabilityTlv.listIterator();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530895
896 while (listIterator.hasNext()) {
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530897 BgpValueType tlv = listIterator.next();
Vidyashree Ramaee293252015-11-18 17:00:11 +0530898 if (tlv.getType() == FOUR_OCTET_AS_NUM_CAPA_TYPE) {
899 isFourOctetCapabilityExits = true;
900 capAsNum = ((FourOctetAsNumCapabilityTlv) tlv).getInt();
901 }
902 }
903
904 if (peerCfg.getAsNumber() > MAX_AS2_NUM) {
905 if (openMsg.getAsNumber() != AS_TRANS) {
906 return false;
907 }
908
909 if (!isFourOctetCapabilityExits) {
910 return false;
911 }
912
913 if (peerCfg.getAsNumber() != capAsNum) {
914 return false;
915 }
916
917 isIbgpSession = peerCfg.getIsIBgp();
918 if (isIbgpSession) {
919 // IBGP - AS number should be same for Peer and local if it is IBGP
920 if (h.bgpconfig.getAsNumber() != capAsNum) {
921 return false;
922 }
923 }
924 } else {
925
926 if (openMsg.getAsNumber() != peerCfg.getAsNumber()) {
927 return false;
928 }
929
930 if (isFourOctetCapabilityExits) {
931 if (capAsNum != peerCfg.getAsNumber()) {
932 return false;
933 }
934 }
935
936 isIbgpSession = peerCfg.getIsIBgp();
937 if (isIbgpSession) {
938 // IBGP - AS number should be same for Peer and local if it is IBGP
939 if (openMsg.getAsNumber() != h.bgpconfig.getAsNumber()) {
940 return false;
941 }
942 }
943 }
944 return true;
945 }
946
947 /**
948 * Validates BGP ID.
949 *
950 * @param openMsg open message
951 * @return true or false
952 */
Shashikanth VH5dd8dbe2015-11-26 13:22:18 +0530953 private boolean bgpIdValidation(BgpOpenMsg openMsg) {
Vidyashree Ramaee293252015-11-18 17:00:11 +0530954 String openMsgBgpId = Ip4Address.valueOf(openMsg.getBgpId()).toString();
955
956 InetAddress ipAddress;
957 try {
958 ipAddress = InetAddress.getByName(openMsgBgpId);
959 if (ipAddress.isMulticastAddress()) {
960 return false;
961 }
962 } catch (UnknownHostException e) {
963 log.debug("InetAddress convertion failed");
964 }
Shashikanth VH6de20d32015-10-09 12:04:13 +0530965 return true;
966 }
967}