1ac782723c57f2f48f6256600bafca2abdba693e
[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 com.google.common.base.Preconditions;
12
13 import io.netty.buffer.ByteBufUtil;
14 import io.netty.channel.ChannelHandler;
15 import io.netty.channel.ChannelHandlerContext;
16 import io.netty.channel.SimpleChannelInboundHandler;
17 import io.netty.channel.socket.DatagramPacket;
18
19 import java.net.InetAddress;
20 import java.nio.ByteBuffer;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Objects;
26
27 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
28 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
29 import org.opendaylight.lispflowmapping.dsbackend.DataStoreBackEnd;
30 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
31 import org.opendaylight.lispflowmapping.lisp.authentication.ILispAuthentication;
32 import org.opendaylight.lispflowmapping.lisp.authentication.LispAuthenticationUtil;
33 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
34 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
35 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
36 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
37 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
38 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
39 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
40 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
41 import org.opendaylight.lispflowmapping.mapcache.SimpleMapCache;
42 import org.opendaylight.lispflowmapping.southbound.LispSouthboundPlugin;
43 import org.opendaylight.lispflowmapping.southbound.LispSouthboundStats;
44 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterCache;
45 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterPartialDeserializer;
46 import org.opendaylight.lispflowmapping.southbound.lisp.exception.LispMalformedPacketException;
47 import org.opendaylight.lispflowmapping.southbound.lisp.network.PacketHeader;
48 import org.opendaylight.lispflowmapping.southbound.util.LispNotificationHelper;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMappingBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotifyBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReplyBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAliveBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMappingBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.key.container.MapRegisterCacheKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadata;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadataBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddress;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddressBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValue;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValueBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
74 import org.opendaylight.yangtools.yang.binding.Notification;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 @ChannelHandler.Sharable
79 public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramPacket>
80         implements ILispSouthboundService, AutoCloseable {
81     private MapRegisterCache mapRegisterCache;
82     private boolean mapRegisterCacheEnabled = true;
83
84     /**
85      * How long is record supposed to be relevant. After this time record isn't valid.
86      *
87      * If you modify this value, please update the LispSouthboundServiceTest class too.
88      */
89     private static final long CACHE_RECORD_TIMEOUT = 90000;
90     private DataBroker dataBroker;
91
92     private NotificationPublishService notificationPublishService;
93     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
94
95     //TODO: think whether this field can be accessed through mappingservice or some other configuration parameter
96     private boolean authenticationEnabled = true;
97
98     private final LispSouthboundPlugin lispSbPlugin;
99     private LispSouthboundStats lispSbStats = null;
100     private SimpleMapCache smc;
101     private AuthenticationKeyDataListener authenticationKeyDataListener;
102     private DataStoreBackEnd dsbe;
103
104     public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
105         this.lispSbPlugin = lispSbPlugin;
106         if (lispSbPlugin != null) {
107             this.lispSbStats = lispSbPlugin.getStats();
108         }
109         this.mapRegisterCache = new MapRegisterCache();
110         this.smc = new SimpleMapCache(new HashMapDb());
111     }
112
113     public void handlePacket(DatagramPacket msg) {
114         ByteBuffer inBuffer = msg.content().nioBuffer();
115         int type = ByteUtil.getUnsignedByte(inBuffer, LispMessage.Pos.TYPE) >> 4;
116         handleStats(type);
117         Object lispType = MessageType.forValue(type);
118         if (lispType == MessageType.EncapsulatedControlMessage) {
119             LOG.trace("Received packet of type Encapsulated Control Message");
120             handleEncapsulatedControlMessage(inBuffer, msg.sender().getAddress());
121         } else if (lispType == MessageType.MapRequest) {
122             LOG.trace("Received packet of type Map-Request");
123             handleMapRequest(inBuffer, msg.sender().getPort());
124         } else if (lispType == MessageType.MapRegister) {
125             LOG.trace("Received packet of type Map-Register");
126             handleMapRegister(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
127         } else if (lispType == MessageType.MapNotify) {
128             LOG.trace("Received packet of type Map-Notify");
129             handleMapNotify(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
130         } else if (lispType == MessageType.MapReply) {
131             LOG.trace("Received packet of type Map-Reply");
132             handleMapReply(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
133         } else {
134             LOG.warn("Received unknown LISP control packet (type " + ((lispType != null) ? lispType : type) + ")");
135         }
136     }
137
138     private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
139         try {
140             handleMapRequest(inBuffer, extractEncapsulatedSourcePort(inBuffer));
141         } catch (RuntimeException re) {
142             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
143                     + inBuffer.capacity() + ")", re);
144         }
145     }
146
147     private void handleMapRequest(ByteBuffer inBuffer, int port) {
148         try {
149             MapRequest request = MapRequestSerializer.getInstance().deserialize(inBuffer);
150             InetAddress finalSourceAddress = MapRequestUtil.selectItrRloc(request);
151             if (finalSourceAddress == null) {
152                 throw new LispMalformedPacketException("Couldn't deserialize Map-Request, no ITR Rloc found!");
153             }
154
155             RequestMappingBuilder requestMappingBuilder = new RequestMappingBuilder();
156             requestMappingBuilder.setMapRequest(LispNotificationHelper.convertMapRequest(request));
157             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
158             transportAddressBuilder.setIpAddress(
159                     LispNotificationHelper.getIpAddressBinaryFromInetAddress(finalSourceAddress));
160             transportAddressBuilder.setPort(new PortNumber(port));
161             requestMappingBuilder.setTransportAddress(transportAddressBuilder.build());
162             if (notificationPublishService != null) {
163                 notificationPublishService.putNotification(requestMappingBuilder.build());
164                 LOG.trace("MapRequest was published!");
165             } else {
166                 LOG.warn("Notification Provider is null!");
167             }
168         } catch (RuntimeException re) {
169             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
170                     + inBuffer.capacity() + ")", re);
171         } catch (InterruptedException e) {
172             LOG.warn("Notification publication interrupted!");
173         }
174     }
175
176     private int extractEncapsulatedSourcePort(ByteBuffer inBuffer) {
177         try {
178             inBuffer.position(PacketHeader.Length.LISP_ENCAPSULATION);
179             int ipType = (inBuffer.get() >> 4);
180             if (ipType == 4) {
181                 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV4 - 1);
182             } else if (ipType == 6) {
183                 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV6_NO_EXT - 1);
184             } else {
185                 throw new LispMalformedPacketException(
186                         "Couldn't deserialize Map-Request: inner packet has unknown IP version: " + ipType);
187             }
188
189             int encapsulatedSourcePort = inBuffer.getShort() & 0xFFFF;
190             inBuffer.position(inBuffer.position() + PacketHeader.Length.UDP - 2);
191             return encapsulatedSourcePort;
192         } catch (RuntimeException re) {
193             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
194                     + inBuffer.capacity() + ")", re);
195         }
196     }
197
198     private void handleMapRegister(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
199         try {
200             Map.Entry<MapRegisterCacheKey, byte[]> artificialEntry = null;
201             MapRegisterCacheKey cacheKey = null;
202             MapRegisterCacheValue cacheValue = null;
203             if (mapRegisterCacheEnabled) {
204                 artificialEntry = MapRegisterPartialDeserializer.deserializePartially(inBuffer, sourceAddress);
205                 cacheKey = artificialEntry == null ? null : artificialEntry.getKey();
206                 cacheValue = resolveCacheValue(artificialEntry);
207             }
208             if (cacheValue != null) {
209                 MapRegisterCacheMetadata mapRegisterMeta = cacheValue.getMapRegisterCacheMetadata();
210                 LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterMeta.getSiteId(),
211                         mapRegisterMeta.getXtrId());
212                 cacheValue = refreshEntry(cacheKey);
213                 if (cacheValue != null) {
214                     sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
215                     if (cacheValue.getMapRegisterCacheMetadata().isWantMapNotify()) {
216                         sendMapNotifyMsg(inBuffer, sourceAddress, port, cacheValue);
217                     }
218                 }
219                 lispSbStats.incrementCacheHits();
220             } else {
221                 MapRegister mapRegister = MapRegisterSerializer.getInstance().deserialize(inBuffer, sourceAddress);
222                 final MappingAuthkey mappingAuthkey = tryToAuthenticateMessage(mapRegister, inBuffer);
223                 if (mappingAuthkey != null) {
224                     AddMappingBuilder addMappingBuilder = new AddMappingBuilder();
225                     addMappingBuilder.setMapRegister(LispNotificationHelper.convertMapRegister(mapRegister));
226                     TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
227                     transportAddressBuilder.setIpAddress(LispNotificationHelper.getIpAddressBinaryFromInetAddress(
228                             sourceAddress));
229                     transportAddressBuilder.setPort(new PortNumber(port));
230                     addMappingBuilder.setTransportAddress(transportAddressBuilder.build());
231                     sendNotificationIfPossible(addMappingBuilder.build());
232                     if (artificialEntry != null) {
233                         final MapRegisterCacheMetadataBuilder cacheMetadataBldNew = new
234                                 MapRegisterCacheMetadataBuilder();
235                         cacheMetadataBldNew.setEidLispAddress(provideEidPrefixesFromMessage(mapRegister));
236                         cacheMetadataBldNew.setXtrId(mapRegister.getXtrId());
237                         cacheMetadataBldNew.setSiteId(mapRegister.getSiteId());
238                         cacheMetadataBldNew.setWantMapNotify(mapRegister.isWantMapNotify());
239                         cacheMetadataBldNew.setMergeEnabled(mapRegister.isMergeEnabled());
240                         cacheMetadataBldNew.setTimestamp(System.currentTimeMillis());
241
242                         final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
243                         cacheValueBldNew.setPacketData(artificialEntry.getValue());
244                         cacheValueBldNew.setMappingAuthkey(mappingAuthkey);
245                         cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
246
247                         mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
248                     }
249                 }
250                 lispSbStats.incrementCacheMisses();
251             }
252         } catch (RuntimeException re) {
253             throw new LispMalformedPacketException("Couldn't deserialize Map-Register (len="
254                     + inBuffer.capacity() + ")", re);
255         } catch (InterruptedException e) {
256             LOG.warn("Notification publication interrupted!");
257         }
258     }
259
260     private MapRegisterCacheValue refreshEntry(final MapRegisterCacheKey cacheKey) {
261         MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.refreshEntry(cacheKey);
262         if (mapRegisterCacheValue != null) {
263             mapRegisterCacheValue = refreshAuthKeyIfNecessary(mapRegisterCacheValue);
264             mapRegisterCache.addEntry(cacheKey, mapRegisterCacheValue);
265             return mapRegisterCacheValue;
266         }
267         return null;
268     }
269
270     private MapRegisterCacheValue refreshAuthKeyIfNecessary(MapRegisterCacheValue mapRegisterCacheValue) {
271         if (authenticationKeyDataListener.isAuthKeyRefreshing()) {
272             final boolean shouldAuthKeyRefreshingStop = System.currentTimeMillis() - authenticationKeyDataListener
273                     .getAuthKeyRefreshingDate() > CACHE_RECORD_TIMEOUT;
274             if (shouldAuthKeyRefreshingStop) {
275                 authenticationKeyDataListener.setAuthKeyRefreshing(false);
276             } else {
277                 final MappingAuthkey mappingAuthkey = provideAuthenticateKey(mapRegisterCacheValue
278                         .getMapRegisterCacheMetadata().getEidLispAddress());
279
280                 final MapRegisterCacheValueBuilder newMapRegisterCacheValueBuilder = new MapRegisterCacheValueBuilder
281                         (mapRegisterCacheValue);
282                 final MapRegisterCacheMetadataBuilder newMapRegisterCacheMetadataBuilder =
283                         new MapRegisterCacheMetadataBuilder(mapRegisterCacheValue.getMapRegisterCacheMetadata());
284
285                 newMapRegisterCacheValueBuilder.setMappingAuthkey(mappingAuthkey);
286                 newMapRegisterCacheValueBuilder.setMapRegisterCacheMetadata(newMapRegisterCacheMetadataBuilder.build());
287                 return newMapRegisterCacheValueBuilder.build();
288             }
289         }
290
291         return mapRegisterCacheValue;
292
293     }
294
295     private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
296         if (entry != null) {
297             final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
298             if (mapRegisterCacheValue != null) {
299                 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
300                 final long currentTime = System.currentTimeMillis();
301                 if (currentTime - creationTime > CACHE_RECORD_TIMEOUT) {
302                     mapRegisterCache.removeEntry(entry.getKey());
303                     return null;
304                 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
305                     return mapRegisterCacheValue;
306                 }
307             }
308         }
309         return null;
310     }
311
312     private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
313         if (notificationPublishService != null) {
314             notificationPublishService.putNotification(notification);
315             LOG.trace("{} was published.", notification.getClass());
316         } else {
317             LOG.warn("Notification Provider is null!");
318         }
319     }
320
321     private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
322         MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
323         mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
324         return mappingKeepAliveBuilder.build();
325     }
326
327     /**
328      * Returns null if not all of eids have the same value of authentication key
329      */
330     private MappingAuthkey provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
331         MappingAuthkey firstAuthKey = null;
332         for (int i = 0; i < eidLispAddresses.size(); i++) {
333             final Eid eid = eidLispAddresses.get(i).getEid();
334             if (i == 0) {
335                 firstAuthKey = smc.getAuthenticationKey(eid);
336             } else {
337                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
338                 if (!Objects.equals(firstAuthKey, authKey)) {
339                     return null;
340                 }
341             }
342         }
343         return firstAuthKey;
344
345     }
346
347     private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber,
348                                   MapRegisterCacheValue mapRegisterValue) {
349         if (mapRegisterValue.getMappingAuthkey().getKeyType() != null) {
350             ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
351             if (mapRegisterValue.getMappingAuthkey().getKeyType() != 0) {
352                 outBuffer = calculateAndSetNewMAC(outBuffer, mapRegisterValue.getMappingAuthkey().getKeyString());
353             }
354             outBuffer.position(0);
355             lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
356         } else {
357             LOG.error("Map-Register Cache: authentication succeeded, but can't find auth key for sending Map-Notify");
358         }
359     }
360
361     /**
362      * Calculates new message authentication code (MAC) for notify message.
363      *
364      * @param buffer
365      * @return
366      */
367     private ByteBuffer calculateAndSetNewMAC(final ByteBuffer buffer, final String authKey) {
368         final byte[] authenticationData = LispAuthenticationUtil.createAuthenticationData(buffer, authKey);
369         buffer.position(ILispAuthentication.MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
370         buffer.put(authenticationData);
371         return buffer;
372     }
373
374     private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
375         buffer.position(0);
376         byte typeAndFlags = buffer.get(0);
377         // Shift the xTR-ID present and built for an RTR bits to their correct position
378         byte flags = (byte) ((typeAndFlags << 2) & 0x0F);
379         // Set control message type to 4 (Map-Notify)
380         byte type = 0x40;
381         // Combine the nibbles
382         typeAndFlags = (byte) (type | flags);
383         byte[] byteReplacement = new byte[] {typeAndFlags, 0x00, 0x00};
384         buffer.put(byteReplacement);
385
386         return buffer;
387     }
388
389     private List<EidLispAddress> provideEidPrefixesFromMessage(final MapRegister mapRegister) {
390         List<EidLispAddress> eidsResult = new ArrayList<>();
391         for (MappingRecordItem mappingRecordItem : mapRegister.getMappingRecordItem()) {
392             final EidLispAddressBuilder eidLispAddressBuilder = new EidLispAddressBuilder();
393             final Eid eid = mappingRecordItem.getMappingRecord().getEid();
394             eidLispAddressBuilder.setEidLispAddressId(LispAddressStringifier.getString(eid));
395             eidLispAddressBuilder.setEid(eid);
396             eidsResult.add(eidLispAddressBuilder.build());
397         }
398         return eidsResult;
399     }
400
401     /**
402      * Checks whether authentication data is valid.
403      *
404      * Methods pass through all records from map register message. For the EID of the first record it gets
405      * authentication key and does validation of authentication data again this authentication key. If it pass
406      * it just checks for remaining records (and its EID) whether they have the same authenticatin key stored in
407      * simple map cache (smc).
408      *
409      * @param mapRegister
410      * @param byteBuffer
411      * @return Returns authentication key if all of EIDs have the same authentication key or null otherwise
412      */
413     private MappingAuthkey tryToAuthenticateMessage(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
414         if (!authenticationEnabled) {
415             return null;
416         }
417
418         if (smc == null) {
419             LOG.debug("Simple map cache wasn't instantieted and set.");
420             return null;
421         }
422
423         MappingAuthkey firstAuthKey = null;
424         final List<MappingRecordItem> mappingRecords = mapRegister.getMappingRecordItem();
425         for (int i = 0; i < mappingRecords.size(); i++) {
426             final MappingRecordItem recordItem = mappingRecords.get(i);
427             final MappingRecord mappingRecord = recordItem.getMappingRecord();
428             if (i == 0) {
429                 firstAuthKey = smc.getAuthenticationKey(mappingRecord.getEid());
430                 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
431                     return null;
432                 }
433             } else {
434                 final Eid eid = mappingRecord.getEid();
435                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
436                 if (!firstAuthKey.equals(authKey)) {
437                     LOG.debug("Map register packet contained several eids. Authentication keys for first one and for " +
438                             "{} are different.",LispAddressStringifier.getString(eid));
439                     return null;
440                 }
441             }
442         }
443         return firstAuthKey;
444     }
445
446     private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
447         try {
448             MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
449             GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
450             gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
451             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
452             transportAddressBuilder.setIpAddress(LispNotificationHelper
453                     .getIpAddressBinaryFromInetAddress(sourceAddress));
454             transportAddressBuilder.setPort(new PortNumber(port));
455             gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
456             if (notificationPublishService != null) {
457                 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
458                 LOG.trace("MapNotify was published!");
459             } else {
460                 LOG.warn("Notification Provider is null!");
461             }
462         } catch (RuntimeException re) {
463             throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
464                     + inBuffer.capacity() + ")", re);
465         } catch (InterruptedException e) {
466             LOG.warn("Notification publication interrupted!");
467         }
468     }
469
470
471     private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
472         try {
473             MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
474             GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
475             gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
476             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
477             transportAddressBuilder.setIpAddress(LispNotificationHelper
478                     .getIpAddressBinaryFromInetAddress(sourceAddress));
479             transportAddressBuilder.setPort(new PortNumber(port));
480             gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
481             if (notificationPublishService != null) {
482                 notificationPublishService.putNotification(gotMapReplyBuilder.build());
483                 LOG.trace("MapReply was published!");
484             } else {
485                 LOG.warn("Notification Provider is null!");
486             }
487         } catch (RuntimeException re) {
488             throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
489                     + inBuffer.capacity() + ")", re);
490         } catch (InterruptedException e) {
491             LOG.warn("Notification publication interrupted!");
492         }
493     }
494
495     private void handleStats(int type) {
496         if (lispSbStats != null) {
497             if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
498                 lispSbStats.incrementRx(type);
499             } else {
500                 lispSbStats.incrementRxUnknown();
501             }
502         }
503     }
504
505     @Override
506     protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
507         if (LOG.isTraceEnabled()) {
508             LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
509                     msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
510         }
511         handlePacket(msg);
512     }
513
514     @Override
515     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
516         ctx.flush();
517     }
518
519     @Override
520     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
521         LOG.error("Error on channel: " + cause, cause);
522     }
523
524     @Override
525     public void close() throws Exception {
526         authenticationKeyDataListener.closeDataChangeListener();
527     }
528
529     public void setSimpleMapCache(final SimpleMapCache smc) {
530         this.smc = smc;
531     }
532
533     public void setDataBroker(final DataBroker dataBroker) {
534         this.dataBroker = dataBroker;
535     }
536
537     public void setNotificationProvider(NotificationPublishService nps) {
538         this.notificationPublishService = nps;
539     }
540
541     public void setMapRegisterCache(final MapRegisterCache mapRegisterCache) {
542         this.mapRegisterCache = mapRegisterCache;
543     }
544
545     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
546         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
547     }
548
549     /**
550     * Restore all keys from MDSAL datastore
551     */
552    public void restoreDaoFromDatastore() {
553        final List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
554        LOG.info("Restoring {} keys from datastore into southbound DAO", authKeys.size());
555
556        for (AuthenticationKey authKey : authKeys) {
557            final Eid key = authKey.getEid();
558            final MappingAuthkey mappingAuthkey = authKey.getMappingAuthkey();
559            LOG.debug("Adding authentication key '{}' with key-ID {} for {}", mappingAuthkey.getKeyString(),
560                    mappingAuthkey.getKeyType(),
561                    LispAddressStringifier.getString(key));
562            smc.addAuthenticationKey(key, mappingAuthkey);
563        }
564     }
565
566     public void init() {
567         Preconditions.checkNotNull(dataBroker);
568         Preconditions.checkNotNull(smc);
569         this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);
570         dsbe = new DataStoreBackEnd(dataBroker);
571     }
572 }