Bug-5922: inbound IPv6 connection fails if address has zero groups in it
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AbstractBGPSessionNegotiator.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.protocol.bgp.rib.impl;
10
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import io.netty.channel.Channel;
14 import io.netty.channel.ChannelFuture;
15 import io.netty.channel.ChannelFutureListener;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.channel.ChannelInboundHandlerAdapter;
18 import io.netty.util.concurrent.Promise;
19 import java.util.concurrent.TimeUnit;
20 import javax.annotation.concurrent.GuardedBy;
21 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
22 import org.opendaylight.protocol.bgp.parser.BGPError;
23 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
24 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
25 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
26 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
27 import org.opendaylight.protocol.util.Ipv6Util;
28 import org.opendaylight.protocol.util.Values;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
37 import org.opendaylight.yangtools.yang.binding.Notification;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Bgp Session negotiator. Common for local-to-remote and remote-to-local connections.
43  * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
44  */
45 abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandlerAdapter implements SessionNegotiator {
46     // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
47     private static final int INITIAL_HOLDTIMER = 4;
48
49     /**
50      * @see <a href="http://tools.ietf.org/html/rfc6793">BGP Support for 4-Octet AS Number Space</a>
51      */
52     private static final int AS_TRANS = 23456;
53
54     @VisibleForTesting
55     public enum State {
56         /**
57          * Negotiation has not started yet.
58          */
59         IDLE,
60         /**
61          * We have sent our Open message, and are waiting for the peer's Open message.
62          */
63         OPEN_SENT,
64         /**
65          * We have received the peer's Open message, which is acceptable, and we're waiting the acknowledgement of our
66          * Open message.
67          */
68         OPEN_CONFIRM,
69         /**
70          * The negotiation finished.
71          */
72         FINISHED,
73     }
74
75     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
76     private final BGPPeerRegistry registry;
77     private final Promise<BGPSessionImpl> promise;
78     private final Channel channel;
79     @GuardedBy("this")
80     private State state = State.IDLE;
81     @GuardedBy("this")
82     private BGPSessionImpl session;
83
84     AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
85             final BGPPeerRegistry registry) {
86         this.promise = Preconditions.checkNotNull(promise);
87         this.channel = Preconditions.checkNotNull(channel);
88         this.registry = registry;
89     }
90
91     private synchronized void startNegotiation() {
92         if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
93             return;
94         }
95         // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
96         final IpAddress remoteIp = getRemoteIp();
97         try {
98             // Check if peer is configured in registry before retrieving preferences
99             if (!this.registry.isPeerConfigured(remoteIp)) {
100                 final BGPDocumentedException cause = new BGPDocumentedException(
101                     String.format("BGP peer with ip: %s not configured, check configured peers in : %s", remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
102                 negotiationFailed(cause);
103                 return;
104             }
105
106             final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
107
108             int as = preferences.getMyAs().getValue().intValue();
109             // Set as AS_TRANS if the value is bigger than 2B
110             if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
111                 as = AS_TRANS;
112             }
113             sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
114                 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
115             if (this.state != State.FINISHED) {
116                 this.state = State.OPEN_SENT;
117                 this.channel.eventLoop().schedule(new Runnable() {
118                     @Override
119                     public void run() {
120                         synchronized (AbstractBGPSessionNegotiator.this) {
121                             if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
122                                 AbstractBGPSessionNegotiator.this
123                                     .sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
124                                 negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
125                                 AbstractBGPSessionNegotiator.this.state = State.FINISHED;
126                             }
127                         }
128                     }
129                 }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
130             }
131         } catch (final Exception e) {
132             LOG.warn("Unexpected negotiation failure", e);
133             negotiationFailedCloseChannel(e);
134         }
135     }
136
137     private IpAddress getRemoteIp() {
138         final IpAddress remoteIp = StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
139         if (remoteIp.getIpv6Address() != null) {
140             return new IpAddress(Ipv6Util.getFullForm(remoteIp.getIpv6Address()));
141         }
142         return remoteIp;
143     }
144
145     protected synchronized void handleMessage(final Notification msg) {
146         LOG.debug("Channel {} handling message in state {}, msg: {}", this.channel, this.state, msg);
147         switch (this.state) {
148         case FINISHED:
149             sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
150             return;
151         case IDLE:
152             // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
153             if (msg instanceof Open) {
154                 startNegotiation();
155                 handleOpen((Open) msg);
156                 return;
157             }
158             sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
159             break;
160         case OPEN_CONFIRM:
161             if (msg instanceof Keepalive) {
162                 negotiationSuccessful(this.session);
163                 LOG.info("BGP Session with peer {} established successfully.", this.channel);
164             } else if (msg instanceof Notify) {
165                 final Notify ntf = (Notify) msg;
166                 negotiationFailed(new BGPDocumentedException("Peer refusal", BGPError.forValue(ntf.getErrorCode(), ntf.getErrorSubcode())));
167             }
168             this.state = State.FINISHED;
169             return;
170         case OPEN_SENT:
171             if (msg instanceof Open) {
172                 handleOpen((Open) msg);
173                 return;
174             }
175             break;
176         default:
177             break;
178         }
179
180         // Catch-all for unexpected message
181         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
182         sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
183         negotiationFailed(new BGPDocumentedException("Unexpected message channel: " + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
184         this.state = State.FINISHED;
185     }
186
187     private static Notify buildErrorNotify(final BGPError err) {
188         return buildErrorNotify(err, null);
189     }
190
191     private static Notify buildErrorNotify(final BGPError err, final byte[] data) {
192         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(err.getCode()).setErrorSubcode(err.getSubcode());
193         if (data != null && data.length != 0) {
194             builder.setData(data);
195         }
196         return builder.build();
197     }
198
199     private synchronized void handleOpen(final Open openObj) {
200         final IpAddress remoteIp = getRemoteIp();
201         final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
202         try {
203             final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences), getDestinationId(openObj, preferences), openObj);
204             sendMessage(new KeepaliveBuilder().build());
205             this.state = State.OPEN_CONFIRM;
206             this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
207             this.session.setChannelExtMsgCoder(openObj);
208             LOG.debug("Channel {} moved to OPEN_CONFIRM state with remote proposal {}", this.channel, openObj);
209         } catch (final BGPDocumentedException e) {
210             LOG.warn("Channel {} negotiation failed", this.channel, e);
211             negotiationFailed(e);
212         }
213     }
214
215     private synchronized void negotiationFailed(final Throwable e) {
216         LOG.warn("Channel {} negotiation failed: {}", this.channel, e.getMessage());
217         if (e instanceof BGPDocumentedException) {
218             // although sendMessage() can also result in calling this method, it won't create a cycle. In case sendMessage() fails to
219             // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
220             sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
221         }
222         if (this.state == State.OPEN_CONFIRM) {
223             this.registry.removePeerSession(getRemoteIp());
224         }
225         negotiationFailedCloseChannel(e);
226         this.state = State.FINISHED;
227     }
228
229     /**
230      * @param openMsg Open message received from remote BGP speaker
231      * @param preferences Local BGP speaker preferences
232      * @return BGP Id of device that accepted the connection
233      */
234     protected abstract Ipv4Address getDestinationId(final Open openMsg, final BGPSessionPreferences preferences);
235
236     /**
237      * @param openMsg Open message received from remote BGP speaker
238      * @param preferences Local BGP speaker preferences
239      * @return BGP Id of device that accepted the connection
240      */
241     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
242
243     public synchronized State getState() {
244         return this.state;
245     }
246
247     private void negotiationSuccessful(final BGPSessionImpl session) {
248         LOG.debug("Negotiation on channel {} successful with session {}", this.channel, session);
249         this.channel.pipeline().replace(this, "session", session);
250         this.promise.setSuccess(session);
251     }
252
253     private void negotiationFailedCloseChannel(final Throwable cause) {
254         LOG.debug("Negotiation on channel {} failed", this.channel, cause);
255         this.channel.close();
256         this.promise.setFailure(cause);
257     }
258
259     private void sendMessage(final Notification msg) {
260         this.channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
261             @Override
262             public void operationComplete(final ChannelFuture f) {
263                 if (!f.isSuccess()) {
264                     LOG.warn("Failed to send message {} to channel {}", msg,  AbstractBGPSessionNegotiator.this.channel, f.cause());
265                     negotiationFailedCloseChannel(f.cause());
266                 } else {
267                     LOG.trace("Message {} sent to channel {}", msg, AbstractBGPSessionNegotiator.this.channel);
268                 }
269             }
270         });
271     }
272
273     @Override
274     public final void channelActive(final ChannelHandlerContext ctx) {
275         LOG.debug("Starting session negotiation on channel {}", this.channel);
276         startNegotiation();
277     }
278
279     @Override
280     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
281         LOG.debug("Negotiation read invoked on channel {}", this.channel);
282         try {
283             handleMessage((Notification) msg);
284         } catch (final Exception e) {
285             LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
286             negotiationFailedCloseChannel(e);
287         }
288
289     }
290
291     @Override
292     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
293         LOG.info("Unexpected error during negotiation", cause);
294         negotiationFailedCloseChannel(cause);
295     }
296 }