BGPCEP-577: Neighbor’s local AS configurable
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / StrictBGPPeerRegistry.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 static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.Maps;
17 import com.google.common.net.InetAddresses;
18 import com.google.common.primitives.UnsignedInts;
19 import io.netty.buffer.ByteBuf;
20 import io.netty.buffer.Unpooled;
21 import java.net.Inet4Address;
22 import java.net.Inet6Address;
23 import java.net.InetAddress;
24 import java.net.InetSocketAddress;
25 import java.net.SocketAddress;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Set;
31 import javax.annotation.concurrent.GuardedBy;
32 import javax.annotation.concurrent.ThreadSafe;
33 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
34 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
35 import org.opendaylight.protocol.bgp.parser.BGPError;
36 import org.opendaylight.protocol.bgp.parser.impl.message.open.As4CapabilityHandler;
37 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
38 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
39 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistryListener;
40 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistrySessionListener;
41 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
42 import org.opendaylight.protocol.util.Ipv6Util;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.Open;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.BgpParameters;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.OptionalCapabilities;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.CParameters;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapability;
53 import org.opendaylight.yangtools.concepts.AbstractRegistration;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * BGP peer registry that allows only 1 session per BGP peer.
59  * If second session with peer is established, one of the sessions will be dropped.
60  * The session with lower source BGP id will be dropped.
61  */
62 @ThreadSafe
63 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
64
65     private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
66
67     @GuardedBy("this")
68     private final Map<IpAddress, BGPSessionListener> peers = Maps.newHashMap();
69     @GuardedBy("this")
70     private final Map<IpAddress, BGPSessionId> sessionIds = Maps.newHashMap();
71     @GuardedBy("this")
72     private final Map<IpAddress, BGPSessionPreferences> peerPreferences = Maps.newHashMap();
73     @GuardedBy("this")
74     private final Set<PeerRegistryListener> listeners = new HashSet<>();
75     @GuardedBy("this")
76     private final Set<PeerRegistrySessionListener> sessionListeners = new HashSet<>();
77
78     public static BGPPeerRegistry instance() {
79         return new StrictBGPPeerRegistry();
80     }
81
82     @Override
83     public synchronized void addPeer(final IpAddress oldIp, final BGPSessionListener peer,
84             final BGPSessionPreferences preferences) {
85         IpAddress fullIp = getFullIp(oldIp);
86         Preconditions.checkArgument(!this.peers.containsKey(fullIp),
87                 "Peer for %s already present", fullIp);
88         this.peers.put(fullIp, requireNonNull(peer));
89         requireNonNull(preferences.getMyAs());
90         requireNonNull(preferences.getParams());
91         requireNonNull(preferences.getBgpId());
92         this.peerPreferences.put(fullIp, preferences);
93         for (final PeerRegistryListener peerRegistryListener : this.listeners) {
94             peerRegistryListener.onPeerAdded(fullIp, preferences);
95         }
96     }
97
98     private IpAddress getFullIp(final IpAddress ip) {
99         requireNonNull(ip);
100         if (ip.getIpv6Address() != null) {
101             return new IpAddress(Ipv6Util.getFullForm(ip.getIpv6Address()));
102         }
103         return ip;
104     }
105
106     @Override
107     public synchronized void removePeer(final IpAddress oldIp) {
108         IpAddress fullIp = getFullIp(oldIp);
109         this.peers.remove(fullIp);
110         for (final PeerRegistryListener peerRegistryListener : this.listeners) {
111             peerRegistryListener.onPeerRemoved(fullIp);
112         }
113     }
114
115     @Override
116     public synchronized void removePeerSession(final IpAddress oldIp) {
117         IpAddress fullIp = getFullIp(oldIp);
118         this.sessionIds.remove(fullIp);
119         for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
120             peerRegistrySessionListener.onSessionRemoved(fullIp);
121         }
122     }
123
124     @Override
125     public boolean isPeerConfigured(final IpAddress oldIp) {
126         IpAddress fullIp = getFullIp(oldIp);
127         return this.peers.containsKey(fullIp);
128     }
129
130     private void checkPeerConfigured(final IpAddress ip) {
131         Preconditions.checkState(isPeerConfigured(ip),
132                 "BGP peer with ip: %s not configured, configured peers are: %s",
133                 ip, this.peers.keySet());
134     }
135
136     @Override
137     public synchronized BGPSessionListener getPeer(final IpAddress ip, final Ipv4Address sourceId,
138         final Ipv4Address remoteId, final Open openObj) throws BGPDocumentedException {
139         requireNonNull(ip);
140         requireNonNull(sourceId);
141         requireNonNull(remoteId);
142         final AsNumber remoteAsNumber = AsNumberUtil.advertizedAsNumber(openObj);
143         requireNonNull(remoteAsNumber);
144
145         final BGPSessionPreferences prefs = getPeerPreferences(ip);
146
147         checkPeerConfigured(ip);
148
149         final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId, remoteAsNumber);
150         final BGPSessionListener p = this.peers.get(ip);
151
152         final BGPSessionId previousConnection = this.sessionIds.get(ip);
153
154         if (previousConnection != null) {
155
156             LOG.warn("Duplicate BGP session established with {}", ip);
157
158             // Session reestablished with different ids
159             if (!previousConnection.equals(currentConnection)) {
160                 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip,
161                         currentConnection, previousConnection);
162                 throw new BGPDocumentedException(
163                         String.format("BGP session with %s %s has to be dropped. Same session already present %s",
164                                 ip, currentConnection, previousConnection),
165                         BGPError.CEASE);
166
167                 // Session reestablished with lower source bgp id, dropping current
168             } else if (previousConnection.isHigherDirection(currentConnection) ||
169                     previousConnection.hasHigherAsNumber(currentConnection)) {
170                 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present",
171                         ip, currentConnection);
172                 throw new BGPDocumentedException(
173                         String.format("BGP session with %s initiated %s has to be dropped. "
174                                 + "Opposite session already present", ip, currentConnection), BGPError.CEASE);
175
176                 // Session reestablished with higher source bgp id, dropping previous
177             } else if (currentConnection.isHigherDirection(previousConnection) ||
178                     currentConnection.hasHigherAsNumber(previousConnection)) {
179                 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
180                 this.peers.get(ip).releaseConnection();
181                 return this.peers.get(ip);
182                 // Session reestablished with same source bgp id, dropping current as duplicate
183             } else {
184                 LOG.warn("BGP session with %s initiated from %s to %s has to be dropped. Same session already present",
185                         ip, sourceId, remoteId);
186                 throw new BGPDocumentedException(
187                         String.format("BGP session with %s initiated %s has to be dropped. "
188                                         + "Same session already present", ip, currentConnection), BGPError.CEASE);
189             }
190         }
191         validateAs(remoteAsNumber, openObj, prefs);
192
193         // Map session id to peer IP address
194         this.sessionIds.put(ip, currentConnection);
195         for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
196             peerRegistrySessionListener.onSessionCreated(ip);
197         }
198         return p;
199     }
200
201     private static void validateAs(final AsNumber remoteAs, final Open openObj, final BGPSessionPreferences localPref)
202             throws BGPDocumentedException {
203         if (!remoteAs.equals(localPref.getExpectedRemoteAs())) {
204             LOG.warn("Unexpected remote AS number. Expecting {}, got {}", localPref.getExpectedRemoteAs(), remoteAs);
205             throw new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS);
206         }
207
208         // https://tools.ietf.org/html/rfc6286#section-2.2
209         if (openObj.getBgpIdentifier() != null
210                 && openObj.getBgpIdentifier().getValue().equals(localPref.getBgpId().getValue())) {
211             LOG.warn("Remote and local BGP Identifiers are the same: {}", openObj.getBgpIdentifier());
212             throw new BGPDocumentedException("Remote and local BGP Identifiers are the same.", BGPError.BAD_BGP_ID);
213         }
214         final List<BgpParameters> prefs = openObj.getBgpParameters();
215         if (prefs != null) {
216             if (getAs4BytesCapability(localPref.getParams()).isPresent() && !getAs4BytesCapability(prefs).isPresent()) {
217                 throw new BGPDocumentedException("The peer must advertise AS4Bytes capability.",
218                         BGPError.UNSUPPORTED_CAPABILITY,
219                         serializeAs4BytesCapability(getAs4BytesCapability(localPref.getParams()).get()));
220             }
221             if (!prefs.containsAll(localPref.getParams())) {
222                 LOG.info("BGP Open message session parameters differ, session still accepted.");
223             }
224         } else {
225             throw new BGPDocumentedException("Open message unacceptable. Check the configuration of BGP speaker.",
226                     BGPError.UNSPECIFIC_OPEN_ERROR);
227         }
228     }
229
230     private static Optional<As4BytesCapability> getAs4BytesCapability(final List<BgpParameters> prefs) {
231         for (final BgpParameters param : prefs) {
232             for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
233                 final CParameters cParam = capa.getCParameters();
234                 if (cParam.getAs4BytesCapability() != null) {
235                     return Optional.of(cParam.getAs4BytesCapability());
236                 }
237             }
238         }
239         return Optional.absent();
240     }
241
242     private static byte[] serializeAs4BytesCapability(final As4BytesCapability as4Capability) {
243         final ByteBuf buffer = Unpooled.buffer(1 /*CODE*/ + 1 /*LENGTH*/
244                 + Integer.SIZE / Byte.SIZE /*4 byte value*/);
245         final As4CapabilityHandler serializer = new As4CapabilityHandler();
246         serializer.serializeCapability(new CParametersBuilder().setAs4BytesCapability(as4Capability).build(), buffer);
247         return buffer.array();
248     }
249
250     @Override
251     public BGPSessionPreferences getPeerPreferences(final IpAddress ip) {
252         requireNonNull(ip);
253         checkPeerConfigured(ip);
254         return this.peerPreferences.get(ip);
255     }
256
257     /**
258      * Creates IpAddress from SocketAddress. Only InetSocketAddress
259      * is accepted with inner address: Inet4Address and Inet6Address.
260      *
261      * @param socketAddress socket address to transform
262      * @return IpAddress equivalent to given socket address
263      * @throws IllegalArgumentException if submitted socket address is not InetSocketAddress[ipv4 | ipv6]
264      */
265     public static IpAddress getIpAddress(final SocketAddress socketAddress) {
266         requireNonNull(socketAddress);
267         Preconditions.checkArgument(socketAddress instanceof InetSocketAddress,
268                 "Expecting InetSocketAddress but was %s", socketAddress.getClass());
269         final InetAddress inetAddress = ((InetSocketAddress) socketAddress).getAddress();
270
271         Preconditions.checkArgument(inetAddress instanceof Inet4Address
272                 || inetAddress instanceof Inet6Address, "Expecting %s or %s but was %s",
273                 Inet4Address.class, Inet6Address.class, inetAddress.getClass());
274         return IetfInetUtil.INSTANCE.ipAddressFor(inetAddress);
275     }
276
277     @Override
278     public synchronized void close() {
279         this.peers.clear();
280         this.sessionIds.clear();
281     }
282
283     @Override
284     public String toString() {
285         return MoreObjects.toStringHelper(this)
286             .add("peers", this.peers.keySet())
287             .toString();
288     }
289
290     /**
291      * Session identifier that contains (source Bgp Id) -> (destination Bgp Id) AsNumber is the remoteAs coming from
292      * remote Open message
293      */
294     private static final class BGPSessionId {
295
296         private final Ipv4Address from, to;
297         private final AsNumber asNumber;
298
299         BGPSessionId(final Ipv4Address from, final Ipv4Address to, final AsNumber asNumber) {
300             this.from = requireNonNull(from);
301             this.to = requireNonNull(to);
302             this.asNumber = requireNonNull(asNumber);
303         }
304
305         /**
306          * Equals does not take direction of connection into account id1 -> id2 and id2 -> id1 are equal
307          */
308         @Override
309         public boolean equals(final Object o) {
310             if (this == o) {
311                 return true;
312             }
313             if (o == null || getClass() != o.getClass()) {
314                 return false;
315             }
316
317             final BGPSessionId bGPSessionId = (BGPSessionId) o;
318
319             if (!this.from.equals(bGPSessionId.from) && !this.from.equals(bGPSessionId.to)) {
320                 return false;
321             }
322             if (!this.to.equals(bGPSessionId.to) && !this.to.equals(bGPSessionId.from)) {
323                 return false;
324             }
325
326             return true;
327         }
328
329         @Override
330         public int hashCode() {
331             final int prime = 31;
332             int result = this.from.hashCode() + this.to.hashCode();
333             result = prime * result;
334             return result;
335         }
336
337         /**
338          * Check if this connection is equal to other and if it contains higher source bgp id
339          */
340         boolean isHigherDirection(final BGPSessionId other) {
341             return toLong(this.from) > toLong(other.from);
342         }
343
344         boolean hasHigherAsNumber(final BGPSessionId other) {
345             return this.asNumber.getValue() > other.asNumber.getValue();
346         }
347
348         private static long toLong(final Ipv4Address from) {
349             final int i = InetAddresses.coerceToInteger(InetAddresses.forString(from.getValue()));
350             return UnsignedInts.toLong(i);
351         }
352
353         @Override
354         public String toString() {
355             return MoreObjects.toStringHelper(this)
356                 .add("from", this.from)
357                 .add("to", this.to)
358                 .toString();
359         }
360     }
361
362     @Override
363     public synchronized AutoCloseable registerPeerRegisterListener(final PeerRegistryListener listener) {
364         this.listeners.add(listener);
365         for (final Entry<IpAddress, BGPSessionPreferences> entry : this.peerPreferences.entrySet()) {
366             listener.onPeerAdded(entry.getKey(), entry.getValue());
367         }
368         return new AbstractRegistration() {
369             @Override
370             protected void removeRegistration() {
371                 synchronized (StrictBGPPeerRegistry.this) {
372                     StrictBGPPeerRegistry.this.listeners.remove(listener);
373                 }
374             }
375         };
376     }
377
378     @Override
379     public synchronized AutoCloseable registerPeerSessionListener(final PeerRegistrySessionListener listener) {
380         this.sessionListeners.add(listener);
381         for (final IpAddress ipAddress : this.sessionIds.keySet()) {
382             listener.onSessionCreated(ipAddress);
383         }
384         return new AbstractRegistration() {
385             @Override
386             protected void removeRegistration() {
387                 synchronized (StrictBGPPeerRegistry.this) {
388                     StrictBGPPeerRegistry.this.sessionListeners.remove(listener);
389                 }
390             }
391         };
392     }
393 }