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