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