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