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