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 io.netty.buffer.ByteBufUtil;
12 import io.netty.channel.ChannelHandler;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.SimpleChannelInboundHandler;
15 import io.netty.channel.socket.DatagramPacket;
16 import java.net.InetAddress;
17 import java.nio.ByteBuffer;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.List;
22 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
23 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
24 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
25 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
26 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
27 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
28 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
29 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
30 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
31 import org.opendaylight.lispflowmapping.southbound.LispSouthboundPlugin;
32 import org.opendaylight.lispflowmapping.southbound.LispSouthboundStats;
33 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterCache;
34 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterPartialDeserializer;
35 import org.opendaylight.lispflowmapping.southbound.lisp.exception.LispMalformedPacketException;
36 import org.opendaylight.lispflowmapping.southbound.lisp.network.PacketHeader;
37 import org.opendaylight.lispflowmapping.southbound.util.LispNotificationHelper;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMappingBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotifyBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReplyBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAliveBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMappingBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.key.container.MapRegisterCacheKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadata;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadataBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddress;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddressBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValue;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValueBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
60 import org.opendaylight.yangtools.yang.binding.Notification;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 @ChannelHandler.Sharable
65 public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramPacket>
66 implements ILispSouthboundService {
67 private final MapRegisterCache mapRegisterCache;
70 * How long is record supposed to be relevant. After this time record isn't valid.
72 * If you modify this value, please update the LispSouthboundServiceTest class too.
74 private static final long CACHE_RECORD_TIMEOUT = 90000;
76 private NotificationPublishService notificationPublishService;
77 protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
79 private final LispSouthboundPlugin lispSbPlugin;
80 private LispSouthboundStats lispSbStats = null;
82 public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin, final MapRegisterCache mapRegisterCache) {
83 this.lispSbPlugin = lispSbPlugin;
84 if (lispSbPlugin != null) {
85 this.lispSbStats = lispSbPlugin.getStats();
87 this.mapRegisterCache = mapRegisterCache;
90 public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
91 this(lispSbPlugin, new MapRegisterCache());
94 public void setNotificationProvider(NotificationPublishService nps) {
95 this.notificationPublishService = nps;
98 public void handlePacket(DatagramPacket msg) {
99 ByteBuffer inBuffer = msg.content().nioBuffer();
100 int type = ByteUtil.getUnsignedByte(inBuffer, LispMessage.Pos.TYPE) >> 4;
102 Object lispType = MessageType.forValue(type);
103 if (lispType == MessageType.EncapsulatedControlMessage) {
104 LOG.trace("Received packet of type Encapsulated Control Message");
105 handleEncapsulatedControlMessage(inBuffer, msg.sender().getAddress());
106 } else if (lispType == MessageType.MapRequest) {
107 LOG.trace("Received packet of type Map-Request");
108 handleMapRequest(inBuffer, msg.sender().getPort());
109 } else if (lispType == MessageType.MapRegister) {
110 LOG.trace("Received packet of type Map-Register");
111 handleMapRegister(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
112 } else if (lispType == MessageType.MapNotify) {
113 LOG.trace("Received packet of type Map-Notify");
114 handleMapNotify(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
115 } else if (lispType == MessageType.MapReply) {
116 LOG.trace("Received packet of type Map-Reply");
117 handleMapReply(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
119 LOG.warn("Received unknown LISP control packet (type " + ((lispType != null) ? lispType : type) + ")");
123 private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
125 handleMapRequest(inBuffer, extractEncapsulatedSourcePort(inBuffer));
126 } catch (RuntimeException re) {
127 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
128 + inBuffer.capacity() + ")", re);
132 private void handleMapRequest(ByteBuffer inBuffer, int port) {
134 MapRequest request = MapRequestSerializer.getInstance().deserialize(inBuffer);
135 InetAddress finalSourceAddress = MapRequestUtil.selectItrRloc(request);
136 if (finalSourceAddress == null) {
137 throw new LispMalformedPacketException("Couldn't deserialize Map-Request, no ITR Rloc found!");
140 RequestMappingBuilder requestMappingBuilder = new RequestMappingBuilder();
141 requestMappingBuilder.setMapRequest(LispNotificationHelper.convertMapRequest(request));
142 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
143 transportAddressBuilder.setIpAddress(
144 LispNotificationHelper.getIpAddressBinaryFromInetAddress(finalSourceAddress));
145 transportAddressBuilder.setPort(new PortNumber(port));
146 requestMappingBuilder.setTransportAddress(transportAddressBuilder.build());
147 if (notificationPublishService != null) {
148 notificationPublishService.putNotification(requestMappingBuilder.build());
149 LOG.trace("MapRequest was published!");
151 LOG.warn("Notification Provider is null!");
153 } catch (RuntimeException re) {
154 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
155 + inBuffer.capacity() + ")", re);
156 } catch (InterruptedException e) {
157 LOG.warn("Notification publication interrupted!");
161 private int extractEncapsulatedSourcePort(ByteBuffer inBuffer) {
163 inBuffer.position(PacketHeader.Length.LISP_ENCAPSULATION);
164 int ipType = (inBuffer.get() >> 4);
166 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV4 - 1);
167 } else if (ipType == 6) {
168 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV6_NO_EXT - 1);
170 throw new LispMalformedPacketException(
171 "Couldn't deserialize Map-Request: inner packet has unknown IP version: " + ipType);
174 int encapsulatedSourcePort = inBuffer.getShort() & 0xFFFF;
175 inBuffer.position(inBuffer.position() + PacketHeader.Length.UDP - 2);
176 return encapsulatedSourcePort;
177 } catch (RuntimeException re) {
178 throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
179 + inBuffer.capacity() + ")", re);
183 private void handleMapRegister(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
185 final Map.Entry<MapRegisterCacheKey, byte[]> artificialEntry = MapRegisterPartialDeserializer
186 .deserializePartially(inBuffer, sourceAddress);
187 final MapRegisterCacheKey cacheKey = artificialEntry == null ? null : artificialEntry.getKey();
189 final MapRegisterCacheValue cacheValue = resolveCacheValue(artificialEntry);
190 if (cacheValue != null) {
191 final MapRegisterCacheMetadata mapRegisterValue = cacheValue.getMapRegisterCacheMetadata();
192 LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterValue.getSiteId(),
193 mapRegisterValue.getXtrId());
194 mapRegisterCache.refreshEntry(cacheKey);
195 sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
196 if (mapRegisterValue.isWantMapNotify()) {
197 sendMapNotifyMsg(inBuffer, sourceAddress, port);
200 MapRegister mapRegister = MapRegisterSerializer.getInstance().deserialize(inBuffer, sourceAddress);
201 AddMappingBuilder addMappingBuilder = new AddMappingBuilder();
202 addMappingBuilder.setMapRegister(LispNotificationHelper.convertMapRegister(mapRegister));
203 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
204 transportAddressBuilder.setIpAddress(LispNotificationHelper.getIpAddressBinaryFromInetAddress(
206 transportAddressBuilder.setPort(new PortNumber(port));
207 addMappingBuilder.setTransportAddress(transportAddressBuilder.build());
208 sendNotificationIfPossible(addMappingBuilder.build());
209 if (artificialEntry != null) {
210 final MapRegisterCacheMetadataBuilder cacheMetadataBldNew = new MapRegisterCacheMetadataBuilder();
211 cacheMetadataBldNew.setEidLispAddress(provideEidPrefixesFromMessage(mapRegister));
212 cacheMetadataBldNew.setXtrId(mapRegister.getXtrId());
213 cacheMetadataBldNew.setSiteId(mapRegister.getSiteId());
214 cacheMetadataBldNew.setWantMapNotify(mapRegister.isWantMapNotify());
215 cacheMetadataBldNew.setMergeEnabled(mapRegister.isMergeEnabled());
216 cacheMetadataBldNew.setTimestamp(System.currentTimeMillis());
218 final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
219 cacheValueBldNew.setPacketData(artificialEntry.getValue());
220 cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
222 mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
225 } catch (RuntimeException re) {
226 throw new LispMalformedPacketException("Couldn't deserialize Map-Register (len="
227 + inBuffer.capacity() + ")", re);
228 } catch (InterruptedException e) {
229 LOG.warn("Notification publication interrupted!");
233 private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
235 final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
236 if (mapRegisterCacheValue != null) {
237 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
238 final long currentTime = System.currentTimeMillis();
239 if (currentTime - creationTime > CACHE_RECORD_TIMEOUT) {
240 mapRegisterCache.removeEntry(entry.getKey());
242 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
243 return mapRegisterCacheValue;
250 private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
251 if (notificationPublishService != null) {
252 notificationPublishService.putNotification(notification);
253 LOG.trace("{} was published.", notification.getClass());
255 LOG.warn("Notification Provider is null!");
259 private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
260 MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
261 mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
262 return mappingKeepAliveBuilder.build();
265 private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber) {
266 ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
267 outBuffer.position(0);
268 lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
271 private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
273 //TODO: also reset of authentication data is required. other trello card is opened for this task.
274 byte[] byteReplacement = new byte[] {0x04, 0x00, 0x00};
275 buffer.put(byteReplacement);
279 private List<EidLispAddress> provideEidPrefixesFromMessage(final MapRegister mapRegister) {
280 List<EidLispAddress> eidsResult = new ArrayList<>();
281 for (MappingRecordItem mappingRecordItem : mapRegister.getMappingRecordItem()) {
282 final EidLispAddressBuilder eidLispAddressBuilder = new EidLispAddressBuilder();
283 final Eid eid = mappingRecordItem.getMappingRecord().getEid();
284 eidLispAddressBuilder.setEidLispAddressId(LispAddressStringifier.getString(eid));
285 eidLispAddressBuilder.setEid(eid);
286 eidsResult.add(eidLispAddressBuilder.build());
291 private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
293 MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
294 GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
295 gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
296 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
297 transportAddressBuilder.setIpAddress(LispNotificationHelper
298 .getIpAddressBinaryFromInetAddress(sourceAddress));
299 transportAddressBuilder.setPort(new PortNumber(port));
300 gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
301 if (notificationPublishService != null) {
302 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
303 LOG.trace("MapNotify was published!");
305 LOG.warn("Notification Provider is null!");
307 } catch (RuntimeException re) {
308 throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
309 + inBuffer.capacity() + ")", re);
310 } catch (InterruptedException e) {
311 LOG.warn("Notification publication interrupted!");
315 private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
317 MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
318 GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
319 gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
320 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
321 transportAddressBuilder.setIpAddress(LispNotificationHelper
322 .getIpAddressBinaryFromInetAddress(sourceAddress));
323 transportAddressBuilder.setPort(new PortNumber(port));
324 gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
325 if (notificationPublishService != null) {
326 notificationPublishService.putNotification(gotMapReplyBuilder.build());
327 LOG.trace("MapReply was published!");
329 LOG.warn("Notification Provider is null!");
331 } catch (RuntimeException re) {
332 throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
333 + inBuffer.capacity() + ")", re);
334 } catch (InterruptedException e) {
335 LOG.warn("Notification publication interrupted!");
339 private void handleStats(int type) {
340 if (lispSbStats != null) {
341 if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
342 lispSbStats.incrementRx(type);
344 lispSbStats.incrementRxUnknown();
350 protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
351 if (LOG.isTraceEnabled()) {
352 LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
353 msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
359 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
364 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
365 LOG.error("Error on channel: " + cause, cause);