347a835ddb7d79d17c4210a14d00111836bb2dbe
[lispflowmapping.git] / mappingservice / southbound / src / main / java / org / opendaylight / lispflowmapping / southbound / lisp / LispSouthboundHandler.java
1 /*
2  * Copyright (c) 2014 Contextream, 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.lispflowmapping.southbound.lisp;
10
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;
21 import java.util.Map;
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;
63
64 @ChannelHandler.Sharable
65 public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramPacket>
66         implements ILispSouthboundService {
67     private final MapRegisterCache mapRegisterCache;
68
69     /**
70      * How long is record supposed to be relevant. After this time record isn't valid.
71      *
72      * If you modify this value, please update the LispSouthboundServiceTest class too.
73      */
74     private static final long CACHE_RECORD_TIMEOUT = 90000;
75
76     private NotificationPublishService notificationPublishService;
77     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
78
79     private final LispSouthboundPlugin lispSbPlugin;
80     private LispSouthboundStats lispSbStats = null;
81
82     public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin, final MapRegisterCache mapRegisterCache) {
83         this.lispSbPlugin = lispSbPlugin;
84         if (lispSbPlugin != null) {
85             this.lispSbStats = lispSbPlugin.getStats();
86         }
87         this.mapRegisterCache = mapRegisterCache;
88     }
89
90     public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
91         this(lispSbPlugin, new MapRegisterCache());
92     }
93
94     public void setNotificationProvider(NotificationPublishService nps) {
95         this.notificationPublishService = nps;
96     }
97
98     public void handlePacket(DatagramPacket msg) {
99         ByteBuffer inBuffer = msg.content().nioBuffer();
100         int type = ByteUtil.getUnsignedByte(inBuffer, LispMessage.Pos.TYPE) >> 4;
101         handleStats(type);
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());
118         } else {
119             LOG.warn("Received unknown LISP control packet (type " + ((lispType != null) ? lispType : type) + ")");
120         }
121     }
122
123     private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
124         try {
125             handleMapRequest(inBuffer, extractEncapsulatedSourcePort(inBuffer));
126         } catch (RuntimeException re) {
127             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
128                     + inBuffer.capacity() + ")", re);
129         }
130     }
131
132     private void handleMapRequest(ByteBuffer inBuffer, int port) {
133         try {
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!");
138             }
139
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!");
150             } else {
151                 LOG.warn("Notification Provider is null!");
152             }
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!");
158         }
159     }
160
161     private int extractEncapsulatedSourcePort(ByteBuffer inBuffer) {
162         try {
163             inBuffer.position(PacketHeader.Length.LISP_ENCAPSULATION);
164             int ipType = (inBuffer.get() >> 4);
165             if (ipType == 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);
169             } else {
170                 throw new LispMalformedPacketException(
171                         "Couldn't deserialize Map-Request: inner packet has unknown IP version: " + ipType);
172             }
173
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);
180         }
181     }
182
183     private void handleMapRegister(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
184         try {
185             final Map.Entry<MapRegisterCacheKey, byte[]> artificialEntry = MapRegisterPartialDeserializer
186                     .deserializePartially(inBuffer, sourceAddress);
187             final MapRegisterCacheKey cacheKey = artificialEntry == null ? null : artificialEntry.getKey();
188
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);
198                 }
199             } else {
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(
205                         sourceAddress));
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());
217
218                     final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
219                     cacheValueBldNew.setPacketData(artificialEntry.getValue());
220                     cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
221
222                     mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
223                 }
224             }
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!");
230         }
231     }
232
233     private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
234         if (entry != null) {
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());
241                     return null;
242                 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
243                     return mapRegisterCacheValue;
244                 }
245             }
246         }
247         return null;
248     }
249
250     private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
251         if (notificationPublishService != null) {
252             notificationPublishService.putNotification(notification);
253             LOG.trace("{} was published.", notification.getClass());
254         } else {
255             LOG.warn("Notification Provider is null!");
256         }
257     }
258
259     private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
260         MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
261         mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
262         return mappingKeepAliveBuilder.build();
263     }
264
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);
269     }
270
271     private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
272         buffer.position(0);
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);
276         return buffer;
277     }
278
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());
287         }
288         return eidsResult;
289     }
290
291     private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
292         try {
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!");
304             } else {
305                 LOG.warn("Notification Provider is null!");
306             }
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!");
312         }
313     }
314
315     private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
316         try {
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!");
328             } else {
329                 LOG.warn("Notification Provider is null!");
330             }
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!");
336         }
337     }
338
339     private void handleStats(int type) {
340         if (lispSbStats != null) {
341             if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
342                 lispSbStats.incrementRx(type);
343             } else {
344                 lispSbStats.incrementRxUnknown();
345             }
346         }
347     }
348
349     @Override
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()));
354         }
355         handlePacket(msg);
356     }
357
358     @Override
359     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
360         ctx.flush();
361     }
362
363     @Override
364     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
365         LOG.error("Error on channel: " + cause, cause);
366     }
367 }