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