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