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 org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
25 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
26 import org.opendaylight.lispflowmapping.southbound.authentication.LispAuthenticationUtil;
27 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
28 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
29 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
30 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
31 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
32 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
33 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
34 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
35 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
36 import org.opendaylight.lispflowmapping.southbound.LispSouthboundPlugin;
37 import org.opendaylight.lispflowmapping.southbound.LispSouthboundStats;
38 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterCache;
39 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterPartialDeserializer;
40 import org.opendaylight.lispflowmapping.southbound.lisp.exception.LispMalformedPacketException;
41 import org.opendaylight.lispflowmapping.southbound.lisp.network.PacketHeader;
42 import org.opendaylight.lispflowmapping.southbound.util.LispNotificationHelper;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMappingBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotifyBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReplyBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAliveBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMappingBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.key.container.MapRegisterCacheKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadata;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadataBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddress;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddressBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValue;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValueBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.mapping.authkey.container.MappingAuthkey;
67 import org.opendaylight.yangtools.yang.binding.Notification;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 @ChannelHandler.Sharable
72 public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramPacket>
73 implements ILispSouthboundService, AutoCloseable {
74 private MapRegisterCache mapRegisterCache;
77 * How long is record supposed to be relevant. After this time record isn't valid.
79 * If you modify this value, please update the LispSouthboundServiceTest class too.
81 private static final long CACHE_RECORD_TIMEOUT = 90000;
82 private DataBroker dataBroker;
84 private NotificationPublishService notificationPublishService;
85 protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
87 //TODO: think whether this field can be accessed through mappingservice or some other configuration parameter
88 private boolean authenticationEnabled = true;
90 private final LispSouthboundPlugin lispSbPlugin;
91 private LispSouthboundStats lispSbStats = null;
92 private SimpleMapCache smc;
93 private AuthenticationKeyDataListener authenticationKeyDataListener;
95 public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
96 this.lispSbPlugin = lispSbPlugin;
97 if (lispSbPlugin != null) {
98 this.lispSbStats = lispSbPlugin.getStats();
100 this.mapRegisterCache = new MapRegisterCache();
101 this.smc = new SimpleMapCache(new HashMapDb());
104 public void handlePacket(DatagramPacket msg) {
105 ByteBuffer inBuffer = msg.content().nioBuffer();
106 int type = ByteUtil.getUnsignedByte(inBuffer, LispMessage.Pos.TYPE) >> 4;
108 Object lispType = MessageType.forValue(type);
109 if (lispType == MessageType.EncapsulatedControlMessage) {
110 LOG.trace("Received packet of type Encapsulated Control Message");
111 handleEncapsulatedControlMessage(inBuffer, msg.sender().getAddress());
112 } else if (lispType == MessageType.MapRequest) {
113 LOG.trace("Received packet of type Map-Request");
114 handleMapRequest(inBuffer, msg.sender().getPort());
115 } else if (lispType == MessageType.MapRegister) {
116 LOG.trace("Received packet of type Map-Register");
117 handleMapRegister(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
118 } else if (lispType == MessageType.MapNotify) {
119 LOG.trace("Received packet of type Map-Notify");
120 handleMapNotify(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
121 } else if (lispType == MessageType.MapReply) {
122 LOG.trace("Received packet of type Map-Reply");
123 handleMapReply(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
125 LOG.warn("Received unknown LISP control packet (type " + ((lispType != null) ? lispType : type) + ")");
129 private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
131 handleMapRequest(inBuffer, extractEncapsulatedSourcePort(inBuffer));
132 } catch (RuntimeException re) {
133 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
134 + inBuffer.capacity() + ")", re);
138 private void handleMapRequest(ByteBuffer inBuffer, int port) {
140 MapRequest request = MapRequestSerializer.getInstance().deserialize(inBuffer);
141 InetAddress finalSourceAddress = MapRequestUtil.selectItrRloc(request);
142 if (finalSourceAddress == null) {
143 throw new LispMalformedPacketException("Couldn't deserialize Map-Request, no ITR Rloc found!");
146 RequestMappingBuilder requestMappingBuilder = new RequestMappingBuilder();
147 requestMappingBuilder.setMapRequest(LispNotificationHelper.convertMapRequest(request));
148 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
149 transportAddressBuilder.setIpAddress(
150 LispNotificationHelper.getIpAddressBinaryFromInetAddress(finalSourceAddress));
151 transportAddressBuilder.setPort(new PortNumber(port));
152 requestMappingBuilder.setTransportAddress(transportAddressBuilder.build());
153 if (notificationPublishService != null) {
154 notificationPublishService.putNotification(requestMappingBuilder.build());
155 LOG.trace("MapRequest was published!");
157 LOG.warn("Notification Provider is null!");
159 } catch (RuntimeException re) {
160 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
161 + inBuffer.capacity() + ")", re);
162 } catch (InterruptedException e) {
163 LOG.warn("Notification publication interrupted!");
167 private int extractEncapsulatedSourcePort(ByteBuffer inBuffer) {
169 inBuffer.position(PacketHeader.Length.LISP_ENCAPSULATION);
170 int ipType = (inBuffer.get() >> 4);
172 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV4 - 1);
173 } else if (ipType == 6) {
174 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV6_NO_EXT - 1);
176 throw new LispMalformedPacketException(
177 "Couldn't deserialize Map-Request: inner packet has unknown IP version: " + ipType);
180 int encapsulatedSourcePort = inBuffer.getShort() & 0xFFFF;
181 inBuffer.position(inBuffer.position() + PacketHeader.Length.UDP - 2);
182 return encapsulatedSourcePort;
183 } catch (RuntimeException re) {
184 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
185 + inBuffer.capacity() + ")", re);
189 private void handleMapRegister(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
191 final Map.Entry<MapRegisterCacheKey, byte[]> artificialEntry = MapRegisterPartialDeserializer
192 .deserializePartially(inBuffer, sourceAddress);
193 final MapRegisterCacheKey cacheKey = artificialEntry == null ? null : artificialEntry.getKey();
195 final MapRegisterCacheValue cacheValue = resolveCacheValue(artificialEntry);
196 if (cacheValue != null) {
197 final MapRegisterCacheMetadata mapRegisterValue = cacheValue.getMapRegisterCacheMetadata();
198 LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterValue.getSiteId(),
199 mapRegisterValue.getXtrId());
200 mapRegisterCache.refreshEntry(cacheKey);
201 sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
202 if (mapRegisterValue.isWantMapNotify()) {
203 sendMapNotifyMsg(inBuffer, sourceAddress, port);
206 MapRegister mapRegister = MapRegisterSerializer.getInstance().deserialize(inBuffer, sourceAddress);
207 if (isAuthenticationSuccessful(mapRegister, inBuffer)) {
208 AddMappingBuilder addMappingBuilder = new AddMappingBuilder();
209 addMappingBuilder.setMapRegister(LispNotificationHelper.convertMapRegister(mapRegister));
210 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
211 transportAddressBuilder.setIpAddress(LispNotificationHelper.getIpAddressBinaryFromInetAddress(
213 transportAddressBuilder.setPort(new PortNumber(port));
214 addMappingBuilder.setTransportAddress(transportAddressBuilder.build());
215 sendNotificationIfPossible(addMappingBuilder.build());
216 if (artificialEntry != null) {
217 final MapRegisterCacheMetadataBuilder cacheMetadataBldNew = new
218 MapRegisterCacheMetadataBuilder();
219 cacheMetadataBldNew.setEidLispAddress(provideEidPrefixesFromMessage(mapRegister));
220 cacheMetadataBldNew.setXtrId(mapRegister.getXtrId());
221 cacheMetadataBldNew.setSiteId(mapRegister.getSiteId());
222 cacheMetadataBldNew.setWantMapNotify(mapRegister.isWantMapNotify());
223 cacheMetadataBldNew.setMergeEnabled(mapRegister.isMergeEnabled());
224 cacheMetadataBldNew.setTimestamp(System.currentTimeMillis());
226 final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
227 cacheValueBldNew.setPacketData(artificialEntry.getValue());
228 cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
230 mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
234 } catch (RuntimeException re) {
235 throw new LispMalformedPacketException("Couldn't deserialize Map-Register (len="
236 + inBuffer.capacity() + ")", re);
237 } catch (InterruptedException e) {
238 LOG.warn("Notification publication interrupted!");
242 private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
244 final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
245 if (mapRegisterCacheValue != null) {
246 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
247 final long currentTime = System.currentTimeMillis();
248 if (currentTime - creationTime > CACHE_RECORD_TIMEOUT) {
249 mapRegisterCache.removeEntry(entry.getKey());
251 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
252 return mapRegisterCacheValue;
259 private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
260 if (notificationPublishService != null) {
261 notificationPublishService.putNotification(notification);
262 LOG.trace("{} was published.", notification.getClass());
264 LOG.warn("Notification Provider is null!");
268 private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
269 MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
270 mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
271 return mappingKeepAliveBuilder.build();
274 private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber) {
275 ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
276 outBuffer.position(0);
277 lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
280 private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
282 //TODO: also reset of authentication data is required. other trello card is opened for this task.
283 byte[] byteReplacement = new byte[] {0x04, 0x00, 0x00};
284 buffer.put(byteReplacement);
288 private List<EidLispAddress> provideEidPrefixesFromMessage(final MapRegister mapRegister) {
289 List<EidLispAddress> eidsResult = new ArrayList<>();
290 for (MappingRecordItem mappingRecordItem : mapRegister.getMappingRecordItem()) {
291 final EidLispAddressBuilder eidLispAddressBuilder = new EidLispAddressBuilder();
292 final Eid eid = mappingRecordItem.getMappingRecord().getEid();
293 eidLispAddressBuilder.setEidLispAddressId(LispAddressStringifier.getString(eid));
294 eidLispAddressBuilder.setEid(eid);
295 eidsResult.add(eidLispAddressBuilder.build());
301 * Checks whether authentication data is valid.
303 * Methods pass through all records from map register message. For the EID of the first record it gets
304 * authentication key and does validation of authentication data again this authentication key. If it pass
305 * it just checks for remaining records (and its EID) whether they have the same authenticatin key stored in
306 * simple map cache (smc).
312 private boolean isAuthenticationSuccessful(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
313 if (!authenticationEnabled) {
318 LOG.debug("Simple map cache wasn't instantieted and set.");
322 MappingAuthkey firstAuthKey = null;
323 final List<MappingRecordItem> mappingRecords = mapRegister.getMappingRecordItem();
324 for (int i = 0; i < mappingRecords.size(); i++) {
325 final MappingRecordItem recordItem = mappingRecords.get(i);
326 final MappingRecord mappingRecord = recordItem.getMappingRecord();
328 firstAuthKey = smc.getAuthenticationKey(mappingRecord.getEid());
329 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
333 final Eid eid = mappingRecord.getEid();
334 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
335 if (!firstAuthKey.equals(authKey)) {
336 LOG.debug("Map register packet contained several eids. Authentication keys for first one and for " +
337 "{} are different.",LispAddressStringifier.getString(eid));
345 private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
347 MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
348 GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
349 gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
350 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
351 transportAddressBuilder.setIpAddress(LispNotificationHelper
352 .getIpAddressBinaryFromInetAddress(sourceAddress));
353 transportAddressBuilder.setPort(new PortNumber(port));
354 gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
355 if (notificationPublishService != null) {
356 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
357 LOG.trace("MapNotify was published!");
359 LOG.warn("Notification Provider is null!");
361 } catch (RuntimeException re) {
362 throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
363 + inBuffer.capacity() + ")", re);
364 } catch (InterruptedException e) {
365 LOG.warn("Notification publication interrupted!");
370 private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
372 MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
373 GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
374 gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
375 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
376 transportAddressBuilder.setIpAddress(LispNotificationHelper
377 .getIpAddressBinaryFromInetAddress(sourceAddress));
378 transportAddressBuilder.setPort(new PortNumber(port));
379 gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
380 if (notificationPublishService != null) {
381 notificationPublishService.putNotification(gotMapReplyBuilder.build());
382 LOG.trace("MapReply was published!");
384 LOG.warn("Notification Provider is null!");
386 } catch (RuntimeException re) {
387 throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
388 + inBuffer.capacity() + ")", re);
389 } catch (InterruptedException e) {
390 LOG.warn("Notification publication interrupted!");
394 private void handleStats(int type) {
395 if (lispSbStats != null) {
396 if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
397 lispSbStats.incrementRx(type);
399 lispSbStats.incrementRxUnknown();
405 protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
406 if (LOG.isTraceEnabled()) {
407 LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
408 msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
414 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
419 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
420 LOG.error("Error on channel: " + cause, cause);
424 public void close() throws Exception {
425 authenticationKeyDataListener.closeDataChangeListener();
428 public void setSimpleMapCache(final SimpleMapCache smc) {
432 public void setDataBroker(final DataBroker dataBroker) {
433 this.dataBroker = dataBroker;
436 public void setNotificationProvider(NotificationPublishService nps) {
437 this.notificationPublishService = nps;
440 public void setMapRegisterCache(final MapRegisterCache mapRegisterCache) {
441 this.mapRegisterCache = mapRegisterCache;
446 Preconditions.checkNotNull(dataBroker);
447 Preconditions.checkNotNull(smc);
448 this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);