Fix Map-Notify for non-authenticated Map-Registers on cache hit
[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> eids) {
287
288         if (eids == null) {
289             LOG.warn("Map-Register Cache: missing EID list when trying to send Map-Notify!");
290             return;
291         }
292
293         final MappingAuthkey authKey = provideAuthenticateKey(eids);
294         if (authKey != null) {
295             ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
296             if (authKey.getKeyType() != 0) {
297                 outBuffer = calculateAndSetNewMAC(outBuffer, authKey.getKeyString());
298             }
299             outBuffer.position(0);
300             lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
301         } else {
302             LOG.error("Map-Register Cache: authentication succeeded, but can't find auth key for sending Map-Notify");
303         }
304     }
305
306     /**
307      * Returns null if not all of eids have the same value of authentication key
308      */
309     private MappingAuthkey provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
310         MappingAuthkey firstAuthKey = null;
311         for (int i = 0; i < eidLispAddresses.size(); i++) {
312             final Eid eid = eidLispAddresses.get(i).getEid();
313             if (i == 0) {
314                 firstAuthKey = smc.getAuthenticationKey(eid);
315             } else {
316                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
317                 if (!Objects.equals(firstAuthKey, authKey)) {
318                     return null;
319                 }
320             }
321         }
322         return firstAuthKey;
323
324     }
325
326     /**
327      * Calculates new message authentication code (MAC) for notify message.
328      *
329      * @param buffer
330      * @return
331      */
332     private ByteBuffer calculateAndSetNewMAC(final ByteBuffer buffer, final String authKey) {
333         final byte[] authenticationData = LispAuthenticationUtil.createAuthenticationData(buffer, authKey);
334         buffer.position(ILispAuthentication.MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
335         buffer.put(authenticationData);
336         return buffer;
337     }
338
339     private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
340         buffer.position(0);
341         byte typeAndFlags = buffer.get(0);
342         // Shift the xTR-ID present and built for an RTR bits to their correct position
343         byte flags = (byte) ((typeAndFlags << 2) & 0x0F);
344         // Set control message type to 4 (Map-Notify)
345         byte type = 0x40;
346         // Combine the nibbles
347         typeAndFlags = (byte) (type | flags);
348         byte[] byteReplacement = new byte[] {typeAndFlags, 0x00, 0x00};
349         buffer.put(byteReplacement);
350
351         return buffer;
352     }
353
354     private List<EidLispAddress> provideEidPrefixesFromMessage(final MapRegister mapRegister) {
355         List<EidLispAddress> eidsResult = new ArrayList<>();
356         for (MappingRecordItem mappingRecordItem : mapRegister.getMappingRecordItem()) {
357             final EidLispAddressBuilder eidLispAddressBuilder = new EidLispAddressBuilder();
358             final Eid eid = mappingRecordItem.getMappingRecord().getEid();
359             eidLispAddressBuilder.setEidLispAddressId(LispAddressStringifier.getString(eid));
360             eidLispAddressBuilder.setEid(eid);
361             eidsResult.add(eidLispAddressBuilder.build());
362         }
363         return eidsResult;
364     }
365
366     /**
367      * Checks whether authentication data is valid.
368      *
369      * Methods pass through all records from map register message. For the EID of the first record it gets
370      * authentication key and does validation of authentication data again this authentication key. If it pass
371      * it just checks for remaining records (and its EID) whether they have the same authenticatin key stored in
372      * simple map cache (smc).
373      *
374      * @param mapRegister
375      * @param byteBuffer
376      * @return
377      */
378     private boolean isAuthenticationSuccessful(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
379         if (!authenticationEnabled) {
380             return true;
381         }
382
383         if (smc == null) {
384             LOG.debug("Simple map cache wasn't instantieted and set.");
385             return false;
386         }
387
388         MappingAuthkey firstAuthKey = null;
389         final List<MappingRecordItem> mappingRecords = mapRegister.getMappingRecordItem();
390         for (int i = 0; i < mappingRecords.size(); i++) {
391             final MappingRecordItem recordItem = mappingRecords.get(i);
392             final MappingRecord mappingRecord = recordItem.getMappingRecord();
393             if (i == 0) {
394                 firstAuthKey = smc.getAuthenticationKey(mappingRecord.getEid());
395                 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
396                     return false;
397                 }
398             } else {
399                 final Eid eid = mappingRecord.getEid();
400                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
401                 if (!firstAuthKey.equals(authKey)) {
402                     LOG.debug("Map register packet contained several eids. Authentication keys for first one and for " +
403                             "{} are different.",LispAddressStringifier.getString(eid));
404                     return false;
405                 }
406             }
407         }
408         return true;
409     }
410
411     private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
412         try {
413             MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
414             GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
415             gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
416             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
417             transportAddressBuilder.setIpAddress(LispNotificationHelper
418                     .getIpAddressBinaryFromInetAddress(sourceAddress));
419             transportAddressBuilder.setPort(new PortNumber(port));
420             gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
421             if (notificationPublishService != null) {
422                 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
423                 LOG.trace("MapNotify was published!");
424             } else {
425                 LOG.warn("Notification Provider is null!");
426             }
427         } catch (RuntimeException re) {
428             throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
429                     + inBuffer.capacity() + ")", re);
430         } catch (InterruptedException e) {
431             LOG.warn("Notification publication interrupted!");
432         }
433     }
434
435
436     private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
437         try {
438             MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
439             GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
440             gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
441             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
442             transportAddressBuilder.setIpAddress(LispNotificationHelper
443                     .getIpAddressBinaryFromInetAddress(sourceAddress));
444             transportAddressBuilder.setPort(new PortNumber(port));
445             gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
446             if (notificationPublishService != null) {
447                 notificationPublishService.putNotification(gotMapReplyBuilder.build());
448                 LOG.trace("MapReply was published!");
449             } else {
450                 LOG.warn("Notification Provider is null!");
451             }
452         } catch (RuntimeException re) {
453             throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
454                     + inBuffer.capacity() + ")", re);
455         } catch (InterruptedException e) {
456             LOG.warn("Notification publication interrupted!");
457         }
458     }
459
460     private void handleStats(int type) {
461         if (lispSbStats != null) {
462             if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
463                 lispSbStats.incrementRx(type);
464             } else {
465                 lispSbStats.incrementRxUnknown();
466             }
467         }
468     }
469
470     @Override
471     protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
472         if (LOG.isTraceEnabled()) {
473             LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
474                     msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
475         }
476         handlePacket(msg);
477     }
478
479     @Override
480     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
481         ctx.flush();
482     }
483
484     @Override
485     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
486         LOG.error("Error on channel: " + cause, cause);
487     }
488
489     @Override
490     public void close() throws Exception {
491         authenticationKeyDataListener.closeDataChangeListener();
492     }
493
494     public void setSimpleMapCache(final SimpleMapCache smc) {
495         this.smc = smc;
496     }
497
498     public void setDataBroker(final DataBroker dataBroker) {
499         this.dataBroker = dataBroker;
500     }
501
502     public void setNotificationProvider(NotificationPublishService nps) {
503         this.notificationPublishService = nps;
504     }
505
506     public void setMapRegisterCache(final MapRegisterCache mapRegisterCache) {
507         this.mapRegisterCache = mapRegisterCache;
508     }
509
510     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
511         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
512     }
513
514     /**
515     * Restore all keys from MDSAL datastore
516     */
517    public void restoreDaoFromDatastore() {
518        final List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
519        LOG.info("Restoring {} keys from datastore into southbound DAO", authKeys.size());
520
521        for (AuthenticationKey authKey : authKeys) {
522            final Eid key = authKey.getEid();
523            final MappingAuthkey mappingAuthkey = authKey.getMappingAuthkey();
524            LOG.debug("Adding authentication key '{}' with key-ID {} for {}", mappingAuthkey.getKeyString(),
525                    mappingAuthkey.getKeyType(),
526                    LispAddressStringifier.getString(key));
527            smc.addAuthenticationKey(key, mappingAuthkey);
528        }
529     }
530
531     public void init() {
532         Preconditions.checkNotNull(dataBroker);
533         Preconditions.checkNotNull(smc);
534         this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);
535         dsbe = new DataStoreBackEnd(dataBroker);
536     }
537 }