2 * Copyright (c) 2014 Contextream, Inc. and others. All rights reserved.
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
9 package org.opendaylight.lispflowmapping.southbound.lisp;
11 import com.google.common.base.Preconditions;
12 import io.netty.buffer.ByteBufUtil;
13 import io.netty.channel.ChannelHandler;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.channel.SimpleChannelInboundHandler;
16 import io.netty.channel.socket.DatagramPacket;
17 import java.net.InetAddress;
18 import java.nio.ByteBuffer;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.List;
23 import java.util.Objects;
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
26 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
27 import org.opendaylight.lispflowmapping.southbound.authentication.LispAuthenticationUtil;
28 import org.opendaylight.lispflowmapping.interfaces.lisp.ILispAuthentication;
29 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
30 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
31 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
32 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
33 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
34 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
35 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
36 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
37 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
38 import org.opendaylight.lispflowmapping.southbound.LispSouthboundPlugin;
39 import org.opendaylight.lispflowmapping.southbound.LispSouthboundStats;
40 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterCache;
41 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterPartialDeserializer;
42 import org.opendaylight.lispflowmapping.southbound.lisp.exception.LispMalformedPacketException;
43 import org.opendaylight.lispflowmapping.southbound.lisp.network.PacketHeader;
44 import org.opendaylight.lispflowmapping.southbound.util.LispNotificationHelper;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMappingBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotifyBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReplyBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAliveBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMappingBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.key.container.MapRegisterCacheKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadata;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadataBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddress;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddressBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValue;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValueBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.mapping.authkey.container.MappingAuthkey;
69 import org.opendaylight.yangtools.yang.binding.Notification;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
73 @ChannelHandler.Sharable
74 public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramPacket>
75 implements ILispSouthboundService, AutoCloseable {
76 private MapRegisterCache mapRegisterCache;
79 * How long is record supposed to be relevant. After this time record isn't valid.
81 * If you modify this value, please update the LispSouthboundServiceTest class too.
83 private static final long CACHE_RECORD_TIMEOUT = 90000;
84 private DataBroker dataBroker;
86 private NotificationPublishService notificationPublishService;
87 protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
89 //TODO: think whether this field can be accessed through mappingservice or some other configuration parameter
90 private boolean authenticationEnabled = true;
92 private final LispSouthboundPlugin lispSbPlugin;
93 private LispSouthboundStats lispSbStats = null;
94 private SimpleMapCache smc;
95 private AuthenticationKeyDataListener authenticationKeyDataListener;
97 public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
98 this.lispSbPlugin = lispSbPlugin;
99 if (lispSbPlugin != null) {
100 this.lispSbStats = lispSbPlugin.getStats();
102 this.mapRegisterCache = new MapRegisterCache();
103 this.smc = new SimpleMapCache(new HashMapDb());
106 public void handlePacket(DatagramPacket msg) {
107 ByteBuffer inBuffer = msg.content().nioBuffer();
108 int type = ByteUtil.getUnsignedByte(inBuffer, LispMessage.Pos.TYPE) >> 4;
110 Object lispType = MessageType.forValue(type);
111 if (lispType == MessageType.EncapsulatedControlMessage) {
112 LOG.trace("Received packet of type Encapsulated Control Message");
113 handleEncapsulatedControlMessage(inBuffer, msg.sender().getAddress());
114 } else if (lispType == MessageType.MapRequest) {
115 LOG.trace("Received packet of type Map-Request");
116 handleMapRequest(inBuffer, msg.sender().getPort());
117 } else if (lispType == MessageType.MapRegister) {
118 LOG.trace("Received packet of type Map-Register");
119 handleMapRegister(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
120 } else if (lispType == MessageType.MapNotify) {
121 LOG.trace("Received packet of type Map-Notify");
122 handleMapNotify(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
123 } else if (lispType == MessageType.MapReply) {
124 LOG.trace("Received packet of type Map-Reply");
125 handleMapReply(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
127 LOG.warn("Received unknown LISP control packet (type " + ((lispType != null) ? lispType : type) + ")");
131 private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
133 handleMapRequest(inBuffer, extractEncapsulatedSourcePort(inBuffer));
134 } catch (RuntimeException re) {
135 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
136 + inBuffer.capacity() + ")", re);
140 private void handleMapRequest(ByteBuffer inBuffer, int port) {
142 MapRequest request = MapRequestSerializer.getInstance().deserialize(inBuffer);
143 InetAddress finalSourceAddress = MapRequestUtil.selectItrRloc(request);
144 if (finalSourceAddress == null) {
145 throw new LispMalformedPacketException("Couldn't deserialize Map-Request, no ITR Rloc found!");
148 RequestMappingBuilder requestMappingBuilder = new RequestMappingBuilder();
149 requestMappingBuilder.setMapRequest(LispNotificationHelper.convertMapRequest(request));
150 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
151 transportAddressBuilder.setIpAddress(
152 LispNotificationHelper.getIpAddressBinaryFromInetAddress(finalSourceAddress));
153 transportAddressBuilder.setPort(new PortNumber(port));
154 requestMappingBuilder.setTransportAddress(transportAddressBuilder.build());
155 if (notificationPublishService != null) {
156 notificationPublishService.putNotification(requestMappingBuilder.build());
157 LOG.trace("MapRequest was published!");
159 LOG.warn("Notification Provider is null!");
161 } catch (RuntimeException re) {
162 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
163 + inBuffer.capacity() + ")", re);
164 } catch (InterruptedException e) {
165 LOG.warn("Notification publication interrupted!");
169 private int extractEncapsulatedSourcePort(ByteBuffer inBuffer) {
171 inBuffer.position(PacketHeader.Length.LISP_ENCAPSULATION);
172 int ipType = (inBuffer.get() >> 4);
174 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV4 - 1);
175 } else if (ipType == 6) {
176 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV6_NO_EXT - 1);
178 throw new LispMalformedPacketException(
179 "Couldn't deserialize Map-Request: inner packet has unknown IP version: " + ipType);
182 int encapsulatedSourcePort = inBuffer.getShort() & 0xFFFF;
183 inBuffer.position(inBuffer.position() + PacketHeader.Length.UDP - 2);
184 return encapsulatedSourcePort;
185 } catch (RuntimeException re) {
186 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
187 + inBuffer.capacity() + ")", re);
191 private void handleMapRegister(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
193 final Map.Entry<MapRegisterCacheKey, byte[]> artificialEntry = MapRegisterPartialDeserializer
194 .deserializePartially(inBuffer, sourceAddress);
195 final MapRegisterCacheKey cacheKey = artificialEntry == null ? null : artificialEntry.getKey();
197 final MapRegisterCacheValue cacheValue = resolveCacheValue(artificialEntry);
198 if (cacheValue != null) {
199 final MapRegisterCacheMetadata mapRegisterValue = cacheValue.getMapRegisterCacheMetadata();
200 LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterValue.getSiteId(),
201 mapRegisterValue.getXtrId());
202 mapRegisterCache.refreshEntry(cacheKey);
203 sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
204 if (mapRegisterValue.isWantMapNotify()) {
205 sendMapNotifyMsg(inBuffer, sourceAddress, port, mapRegisterValue.getEidLispAddress());
208 MapRegister mapRegister = MapRegisterSerializer.getInstance().deserialize(inBuffer, sourceAddress);
209 if (isAuthenticationSuccessful(mapRegister, inBuffer)) {
210 AddMappingBuilder addMappingBuilder = new AddMappingBuilder();
211 addMappingBuilder.setMapRegister(LispNotificationHelper.convertMapRegister(mapRegister));
212 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
213 transportAddressBuilder.setIpAddress(LispNotificationHelper.getIpAddressBinaryFromInetAddress(
215 transportAddressBuilder.setPort(new PortNumber(port));
216 addMappingBuilder.setTransportAddress(transportAddressBuilder.build());
217 sendNotificationIfPossible(addMappingBuilder.build());
218 if (artificialEntry != null) {
219 final MapRegisterCacheMetadataBuilder cacheMetadataBldNew = new
220 MapRegisterCacheMetadataBuilder();
221 cacheMetadataBldNew.setEidLispAddress(provideEidPrefixesFromMessage(mapRegister));
222 cacheMetadataBldNew.setXtrId(mapRegister.getXtrId());
223 cacheMetadataBldNew.setSiteId(mapRegister.getSiteId());
224 cacheMetadataBldNew.setWantMapNotify(mapRegister.isWantMapNotify());
225 cacheMetadataBldNew.setMergeEnabled(mapRegister.isMergeEnabled());
226 cacheMetadataBldNew.setTimestamp(System.currentTimeMillis());
228 final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
229 cacheValueBldNew.setPacketData(artificialEntry.getValue());
230 cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
232 mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
236 } catch (RuntimeException re) {
237 throw new LispMalformedPacketException("Couldn't deserialize Map-Register (len="
238 + inBuffer.capacity() + ")", re);
239 } catch (InterruptedException e) {
240 LOG.warn("Notification publication interrupted!");
244 private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
246 final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
247 if (mapRegisterCacheValue != null) {
248 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
249 final long currentTime = System.currentTimeMillis();
250 if (currentTime - creationTime > CACHE_RECORD_TIMEOUT) {
251 mapRegisterCache.removeEntry(entry.getKey());
253 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
254 return mapRegisterCacheValue;
261 private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
262 if (notificationPublishService != null) {
263 notificationPublishService.putNotification(notification);
264 LOG.trace("{} was published.", notification.getClass());
266 LOG.warn("Notification Provider is null!");
270 private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
271 MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
272 mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
273 return mappingKeepAliveBuilder.build();
276 private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber,
277 List<EidLispAddress> cacheValue) {
279 final String authKey = provideAuthenticateKey(cacheValue);
280 if (authKey != null) {
281 ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
282 outBuffer = calculateAndSetNewMAC(outBuffer, authKey);
283 outBuffer.position(0);
284 lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
289 * Returns null if not all of eids have the same value of authentication key
291 private String provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
292 MappingAuthkey firstAuthKey = null;
293 for (int i = 0; i < eidLispAddresses.size(); i++) {
294 final Eid eid = eidLispAddresses.get(i).getEid();
296 firstAuthKey = smc.getAuthenticationKey(eid);
298 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
299 if (!Objects.equals(firstAuthKey, authKey)) {
304 return firstAuthKey.getKeyString();
309 * Calculates new message authentication code (MAC) for notify message.
314 private ByteBuffer calculateAndSetNewMAC(final ByteBuffer buffer, final String authKey) {
315 final byte[] authenticationData = LispAuthenticationUtil.createAuthenticationData(buffer, authKey);
316 buffer.position(ILispAuthentication.MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
317 buffer.put(authenticationData);
321 private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
323 byte[] byteReplacement = new byte[] {0x04, 0x00, 0x00};
324 buffer.put(byteReplacement);
329 private List<EidLispAddress> provideEidPrefixesFromMessage(final MapRegister mapRegister) {
330 List<EidLispAddress> eidsResult = new ArrayList<>();
331 for (MappingRecordItem mappingRecordItem : mapRegister.getMappingRecordItem()) {
332 final EidLispAddressBuilder eidLispAddressBuilder = new EidLispAddressBuilder();
333 final Eid eid = mappingRecordItem.getMappingRecord().getEid();
334 eidLispAddressBuilder.setEidLispAddressId(LispAddressStringifier.getString(eid));
335 eidLispAddressBuilder.setEid(eid);
336 eidsResult.add(eidLispAddressBuilder.build());
342 * Checks whether authentication data is valid.
344 * Methods pass through all records from map register message. For the EID of the first record it gets
345 * authentication key and does validation of authentication data again this authentication key. If it pass
346 * it just checks for remaining records (and its EID) whether they have the same authenticatin key stored in
347 * simple map cache (smc).
353 private boolean isAuthenticationSuccessful(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
354 if (!authenticationEnabled) {
359 LOG.debug("Simple map cache wasn't instantieted and set.");
363 MappingAuthkey firstAuthKey = null;
364 final List<MappingRecordItem> mappingRecords = mapRegister.getMappingRecordItem();
365 for (int i = 0; i < mappingRecords.size(); i++) {
366 final MappingRecordItem recordItem = mappingRecords.get(i);
367 final MappingRecord mappingRecord = recordItem.getMappingRecord();
369 firstAuthKey = smc.getAuthenticationKey(mappingRecord.getEid());
370 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
374 final Eid eid = mappingRecord.getEid();
375 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
376 if (!firstAuthKey.equals(authKey)) {
377 LOG.debug("Map register packet contained several eids. Authentication keys for first one and for " +
378 "{} are different.",LispAddressStringifier.getString(eid));
386 private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
388 MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
389 GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
390 gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
391 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
392 transportAddressBuilder.setIpAddress(LispNotificationHelper
393 .getIpAddressBinaryFromInetAddress(sourceAddress));
394 transportAddressBuilder.setPort(new PortNumber(port));
395 gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
396 if (notificationPublishService != null) {
397 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
398 LOG.trace("MapNotify was published!");
400 LOG.warn("Notification Provider is null!");
402 } catch (RuntimeException re) {
403 throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
404 + inBuffer.capacity() + ")", re);
405 } catch (InterruptedException e) {
406 LOG.warn("Notification publication interrupted!");
411 private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
413 MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
414 GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
415 gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
416 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
417 transportAddressBuilder.setIpAddress(LispNotificationHelper
418 .getIpAddressBinaryFromInetAddress(sourceAddress));
419 transportAddressBuilder.setPort(new PortNumber(port));
420 gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
421 if (notificationPublishService != null) {
422 notificationPublishService.putNotification(gotMapReplyBuilder.build());
423 LOG.trace("MapReply was published!");
425 LOG.warn("Notification Provider is null!");
427 } catch (RuntimeException re) {
428 throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
429 + inBuffer.capacity() + ")", re);
430 } catch (InterruptedException e) {
431 LOG.warn("Notification publication interrupted!");
435 private void handleStats(int type) {
436 if (lispSbStats != null) {
437 if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
438 lispSbStats.incrementRx(type);
440 lispSbStats.incrementRxUnknown();
446 protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
447 if (LOG.isTraceEnabled()) {
448 LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
449 msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
455 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
460 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
461 LOG.error("Error on channel: " + cause, cause);
465 public void close() throws Exception {
466 authenticationKeyDataListener.closeDataChangeListener();
469 public void setSimpleMapCache(final SimpleMapCache smc) {
473 public void setDataBroker(final DataBroker dataBroker) {
474 this.dataBroker = dataBroker;
477 public void setNotificationProvider(NotificationPublishService nps) {
478 this.notificationPublishService = nps;
481 public void setMapRegisterCache(final MapRegisterCache mapRegisterCache) {
482 this.mapRegisterCache = mapRegisterCache;
487 Preconditions.checkNotNull(dataBroker);
488 Preconditions.checkNotNull(smc);
489 this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);