Handle the case of empty optional capabilities
[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.IpAddressNoZone;
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.Ipv4AddressNoZone;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6AddressNoZone;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.Open;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.open.message.BgpParameters;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.open.message.bgp.parameters.OptionalCapabilities;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.open.message.bgp.parameters.optional.capabilities.CParameters;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapability;
53 import org.opendaylight.yangtools.concepts.AbstractRegistration;
54 import org.opendaylight.yangtools.concepts.Registration;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * BGP peer registry that allows only 1 session per BGP peer. If a second session with peer is established, one of
60  * the sessions will be dropped. The session with lower source BGP id will be dropped. This class is thread-safe.
61  */
62 public final class StrictBGPPeerRegistry implements BGPPeerRegistry {
63     private static final Logger LOG = LoggerFactory.getLogger(StrictBGPPeerRegistry.class);
64
65     @GuardedBy("this")
66     private final Map<IpAddressNoZone, BGPSessionListener> peers = new HashMap<>();
67     @GuardedBy("this")
68     private final Map<IpAddressNoZone, BGPSessionId> sessionIds = new HashMap<>();
69     @GuardedBy("this")
70     private final Map<IpAddressNoZone, BGPSessionPreferences> peerPreferences = new HashMap<>();
71     private final Set<PeerRegistryListener> listeners = ConcurrentHashMap.newKeySet();
72     private final Set<PeerRegistrySessionListener> sessionListeners = ConcurrentHashMap.newKeySet();
73
74     public static BGPPeerRegistry instance() {
75         return new StrictBGPPeerRegistry();
76     }
77
78     @Override
79     public synchronized void addPeer(final IpAddressNoZone oldIp, final BGPSessionListener peer,
80             final BGPSessionPreferences preferences) {
81         IpAddressNoZone fullIp = getFullIp(oldIp);
82         Preconditions.checkArgument(!this.peers.containsKey(fullIp),
83                 "Peer for %s already present", fullIp);
84         this.peers.put(fullIp, requireNonNull(peer));
85         requireNonNull(preferences.getMyAs());
86         requireNonNull(preferences.getParams());
87         requireNonNull(preferences.getBgpId());
88         this.peerPreferences.put(fullIp, preferences);
89         for (final PeerRegistryListener peerRegistryListener : this.listeners) {
90             peerRegistryListener.onPeerAdded(fullIp, preferences);
91         }
92     }
93
94     private static IpAddressNoZone getFullIp(final IpAddressNoZone ip) {
95         final Ipv6AddressNoZone addr = ip.getIpv6AddressNoZone();
96         return addr == null ? ip : new IpAddressNoZone(Ipv6Util.getFullForm(addr));
97     }
98
99     @Override
100     public synchronized void removePeer(final IpAddressNoZone oldIp) {
101         IpAddressNoZone fullIp = getFullIp(oldIp);
102         this.peers.remove(fullIp);
103         for (final PeerRegistryListener peerRegistryListener : this.listeners) {
104             peerRegistryListener.onPeerRemoved(fullIp);
105         }
106     }
107
108     @Override
109     public synchronized void removePeerSession(final IpAddressNoZone oldIp) {
110         IpAddressNoZone fullIp = getFullIp(oldIp);
111         this.sessionIds.remove(fullIp);
112         for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
113             peerRegistrySessionListener.onSessionRemoved(fullIp);
114         }
115     }
116
117     @Override
118     public boolean isPeerConfigured(final IpAddressNoZone oldIp) {
119         IpAddressNoZone fullIp = getFullIp(oldIp);
120         return this.peers.containsKey(fullIp);
121     }
122
123     private void checkPeerConfigured(final IpAddressNoZone ip) {
124         Preconditions.checkState(isPeerConfigured(ip),
125                 "BGP peer with ip: %s not configured, configured peers are: %s",
126                 ip, this.peers.keySet());
127     }
128
129     @Override
130     public synchronized BGPSessionListener getPeer(final IpAddressNoZone ip, final Ipv4AddressNoZone sourceId,
131             final Ipv4AddressNoZone remoteId, final Open openObj) throws BGPDocumentedException {
132         requireNonNull(ip);
133         requireNonNull(sourceId);
134         requireNonNull(remoteId);
135         final AsNumber remoteAsNumber = AsNumberUtil.advertizedAsNumber(openObj);
136         requireNonNull(remoteAsNumber);
137
138         final BGPSessionPreferences prefs = getPeerPreferences(ip);
139
140         checkPeerConfigured(ip);
141
142         final BGPSessionId currentConnection = new BGPSessionId(sourceId, remoteId, remoteAsNumber);
143         final BGPSessionListener p = this.peers.get(ip);
144
145         final BGPSessionId previousConnection = this.sessionIds.get(ip);
146
147         if (previousConnection != null) {
148
149             LOG.warn("Duplicate BGP session established with {}", ip);
150
151             // Session reestablished with different ids
152             if (!previousConnection.equals(currentConnection)) {
153                 LOG.warn("BGP session with {} {} has to be dropped. Same session already present {}", ip,
154                         currentConnection, previousConnection);
155                 throw new BGPDocumentedException(
156                         String.format("BGP session with %s %s has to be dropped. Same session already present %s",
157                                 ip, currentConnection, previousConnection),
158                         BGPError.CEASE);
159
160                 // Session reestablished with lower source bgp id, dropping current
161             } else if (previousConnection.isHigherDirection(currentConnection)
162                     || previousConnection.hasHigherAsNumber(currentConnection)) {
163                 LOG.warn("BGP session with {} {} has to be dropped. Opposite session already present",
164                         ip, currentConnection);
165                 throw new BGPDocumentedException(
166                         String.format("BGP session with %s initiated %s has to be dropped. "
167                                 + "Opposite session already present", ip, currentConnection), BGPError.CEASE);
168
169                 // Session reestablished with higher source bgp id, dropping previous
170             } else if (currentConnection.isHigherDirection(previousConnection)
171                     || currentConnection.hasHigherAsNumber(previousConnection)) {
172                 LOG.warn("BGP session with {} {} released. Replaced by opposite session", ip, previousConnection);
173                 this.peers.get(ip).releaseConnection();
174                 return this.peers.get(ip);
175                 // Session reestablished with same source bgp id, dropping current as duplicate
176             } else {
177                 LOG.warn("BGP session with {} initiated from {} to {} has to be dropped. Same session already present",
178                         ip, sourceId, remoteId);
179                 throw new BGPDocumentedException(
180                         String.format("BGP session with %s initiated %s has to be dropped. "
181                                         + "Same session already present", ip, currentConnection), BGPError.CEASE);
182             }
183         }
184         validateAs(remoteAsNumber, openObj, prefs);
185
186         // Map session id to peer IP address
187         this.sessionIds.put(ip, currentConnection);
188         for (final PeerRegistrySessionListener peerRegistrySessionListener : this.sessionListeners) {
189             peerRegistrySessionListener.onSessionCreated(ip);
190         }
191         return p;
192     }
193
194     private static void validateAs(final AsNumber remoteAs, final Open openObj, final BGPSessionPreferences localPref)
195             throws BGPDocumentedException {
196         if (!remoteAs.equals(localPref.getExpectedRemoteAs())) {
197             LOG.warn("Unexpected remote AS number. Expecting {}, got {}", localPref.getExpectedRemoteAs(), remoteAs);
198             throw new BGPDocumentedException("Peer AS number mismatch", BGPError.BAD_PEER_AS);
199         }
200
201         // https://tools.ietf.org/html/rfc6286#section-2.2
202         if (openObj.getBgpIdentifier() != null
203                 && openObj.getBgpIdentifier().getValue().equals(localPref.getBgpId().getValue())) {
204             LOG.warn("Remote and local BGP Identifiers are the same: {}", openObj.getBgpIdentifier());
205             throw new BGPDocumentedException("Remote and local BGP Identifiers are the same.", BGPError.BAD_BGP_ID);
206         }
207         final List<BgpParameters> prefs = openObj.getBgpParameters();
208         if (prefs != null) {
209             final As4BytesCapability localCap = getAs4BytesCapability(localPref.getParams());
210             if (localCap != null && getAs4BytesCapability(prefs) == null) {
211                 throw new BGPDocumentedException("The peer must advertise AS4Bytes capability.",
212                         BGPError.UNSUPPORTED_CAPABILITY, serializeAs4BytesCapability(localCap));
213             }
214             if (!prefs.containsAll(localPref.getParams())) {
215                 LOG.info("BGP Open message session parameters differ, session still accepted.");
216             }
217         } else {
218             throw new BGPDocumentedException("Open message unacceptable. Check the configuration of BGP speaker.",
219                     BGPError.UNSPECIFIC_OPEN_ERROR);
220         }
221     }
222
223     private static @Nullable As4BytesCapability getAs4BytesCapability(final List<BgpParameters> prefs) {
224         for (final BgpParameters param : prefs) {
225             for (final OptionalCapabilities capa : param.nonnullOptionalCapabilities()) {
226                 final CParameters cParam = capa.getCParameters();
227                 final As4BytesCapability asCapa = cParam.getAs4BytesCapability();
228                 if (asCapa != null) {
229                     return asCapa;
230                 }
231             }
232         }
233         return null;
234     }
235
236     private static byte[] serializeAs4BytesCapability(final As4BytesCapability as4Capability) {
237         final ByteBuf buffer = Unpooled.buffer(1 /*CODE*/ + 1 /*LENGTH*/ + Integer.BYTES /*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 IpAddressNoZone 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 IpAddressNoZone 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.ipAddressNoZoneFor(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<IpAddressNoZone, 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 IpAddressNoZone 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 IpAddressNoZone address, final BGPSessionPreferences preferences) {
386         if (this.peerPreferences.containsKey(address)) {
387             this.peerPreferences.put(address, preferences);
388         }
389     }
390 }