Adding authentication data to map register cache.
[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                 MapRegisterCacheMetadata mapRegisterMeta = cacheValue.getMapRegisterCacheMetadata();
207                 LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterMeta.getSiteId(),
208                         mapRegisterMeta.getXtrId());
209                 mapRegisterMeta = refreshEntry(cacheKey);
210                 sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
211
212                 if (mapRegisterMeta.isWantMapNotify()) {
213                     sendMapNotifyMsg(inBuffer, sourceAddress, port, cacheValue);
214                 }
215                 lispSbStats.incrementCacheHits();
216             } else {
217                 MapRegister mapRegister = MapRegisterSerializer.getInstance().deserialize(inBuffer, sourceAddress);
218                 final MappingAuthkey mappingAuthkey = tryToAuthenticateMessage(mapRegister, inBuffer);
219                 if (mappingAuthkey != null) {
220                     AddMappingBuilder addMappingBuilder = new AddMappingBuilder();
221                     addMappingBuilder.setMapRegister(LispNotificationHelper.convertMapRegister(mapRegister));
222                     TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
223                     transportAddressBuilder.setIpAddress(LispNotificationHelper.getIpAddressBinaryFromInetAddress(
224                             sourceAddress));
225                     transportAddressBuilder.setPort(new PortNumber(port));
226                     addMappingBuilder.setTransportAddress(transportAddressBuilder.build());
227                     sendNotificationIfPossible(addMappingBuilder.build());
228                     if (artificialEntry != null) {
229                         final MapRegisterCacheMetadataBuilder cacheMetadataBldNew = new
230                                 MapRegisterCacheMetadataBuilder();
231                         cacheMetadataBldNew.setEidLispAddress(provideEidPrefixesFromMessage(mapRegister));
232                         cacheMetadataBldNew.setXtrId(mapRegister.getXtrId());
233                         cacheMetadataBldNew.setSiteId(mapRegister.getSiteId());
234                         cacheMetadataBldNew.setWantMapNotify(mapRegister.isWantMapNotify());
235                         cacheMetadataBldNew.setMergeEnabled(mapRegister.isMergeEnabled());
236                         cacheMetadataBldNew.setTimestamp(System.currentTimeMillis());
237
238                         final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
239                         cacheValueBldNew.setPacketData(artificialEntry.getValue());
240                         cacheValueBldNew.setAuthKeyValue(mappingAuthkey.getKeyString());
241                         cacheValueBldNew.setAuthKeyType(mappingAuthkey.getKeyType());
242                         cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
243
244                         mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
245                     }
246                 }
247                 lispSbStats.incrementCacheMisses();
248             }
249         } catch (RuntimeException re) {
250             throw new LispMalformedPacketException("Couldn't deserialize Map-Register (len="
251                     + inBuffer.capacity() + ")", re);
252         } catch (InterruptedException e) {
253             LOG.warn("Notification publication interrupted!");
254         }
255     }
256
257     private MapRegisterCacheMetadata refreshEntry(final MapRegisterCacheKey cacheKey) {
258         MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.refreshEntry(cacheKey);
259         if (mapRegisterCacheValue != null) {
260             mapRegisterCacheValue = refreshAuthKeyIfNecessary(mapRegisterCacheValue);
261             mapRegisterCache.addEntry(cacheKey, mapRegisterCacheValue);
262             return mapRegisterCacheValue.getMapRegisterCacheMetadata();
263         }
264         return null;
265     }
266
267     private MapRegisterCacheValue refreshAuthKeyIfNecessary(MapRegisterCacheValue mapRegisterCacheValue) {
268         if (authenticationKeyDataListener.isAuthKeyRefreshing()) {
269             final boolean shouldAuthKeyRefreshingStop = System.currentTimeMillis() - authenticationKeyDataListener
270                     .getAuthKeyRefreshingDate() > CACHE_RECORD_TIMEOUT;
271             if (shouldAuthKeyRefreshingStop) {
272                 authenticationKeyDataListener.setAuthKeyRefreshing(false);
273             } else {
274                 final MappingAuthkey mappingAuthkey = provideAuthenticateKey(mapRegisterCacheValue
275                         .getMapRegisterCacheMetadata().getEidLispAddress());
276
277                 final MapRegisterCacheValueBuilder newMapRegisterCacheValueBuilder = new MapRegisterCacheValueBuilder
278                         (mapRegisterCacheValue);
279                 final MapRegisterCacheMetadataBuilder newMapRegisterCacheMetadataBuilder =
280                         new MapRegisterCacheMetadataBuilder(mapRegisterCacheValue.getMapRegisterCacheMetadata());
281
282                 newMapRegisterCacheValueBuilder.setAuthKeyValue(mappingAuthkey.getKeyString());
283                 newMapRegisterCacheValueBuilder.setAuthKeyType(mappingAuthkey.getKeyType());
284                 newMapRegisterCacheValueBuilder.setMapRegisterCacheMetadata(newMapRegisterCacheMetadataBuilder.build());
285                 return newMapRegisterCacheValueBuilder.build();
286             }
287         }
288
289         return mapRegisterCacheValue;
290
291     }
292
293     private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
294         if (entry != null) {
295             final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
296             if (mapRegisterCacheValue != null) {
297                 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
298                 final long currentTime = System.currentTimeMillis();
299                 if (currentTime - creationTime > CACHE_RECORD_TIMEOUT) {
300                     mapRegisterCache.removeEntry(entry.getKey());
301                     return null;
302                 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
303                     return mapRegisterCacheValue;
304                 }
305             }
306         }
307         return null;
308     }
309
310     private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
311         if (notificationPublishService != null) {
312             notificationPublishService.putNotification(notification);
313             LOG.trace("{} was published.", notification.getClass());
314         } else {
315             LOG.warn("Notification Provider is null!");
316         }
317     }
318
319     private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
320         MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
321         mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
322         return mappingKeepAliveBuilder.build();
323     }
324
325     /**
326      * Returns null if not all of eids have the same value of authentication key
327      */
328     private MappingAuthkey provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
329         MappingAuthkey firstAuthKey = null;
330         for (int i = 0; i < eidLispAddresses.size(); i++) {
331             final Eid eid = eidLispAddresses.get(i).getEid();
332             if (i == 0) {
333                 firstAuthKey = smc.getAuthenticationKey(eid);
334             } else {
335                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
336                 if (!Objects.equals(firstAuthKey, authKey)) {
337                     return null;
338                 }
339             }
340         }
341         return firstAuthKey;
342
343     }
344
345     private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber,
346                                   MapRegisterCacheValue mapRegisterValue) {
347         if (mapRegisterValue.getAuthKeyType() != null) {
348             ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
349             if (mapRegisterValue.getAuthKeyType() != 0) {
350                 outBuffer = calculateAndSetNewMAC(outBuffer, mapRegisterValue.getAuthKeyValue());
351             }
352             outBuffer.position(0);
353             lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
354         } else {
355             LOG.error("Map-Register Cache: authentication succeeded, but can't find auth key for sending Map-Notify");
356         }
357     }
358
359     /**
360      * Calculates new message authentication code (MAC) for notify message.
361      *
362      * @param buffer
363      * @return
364      */
365     private ByteBuffer calculateAndSetNewMAC(final ByteBuffer buffer, final String authKey) {
366         final byte[] authenticationData = LispAuthenticationUtil.createAuthenticationData(buffer, authKey);
367         buffer.position(ILispAuthentication.MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
368         buffer.put(authenticationData);
369         return buffer;
370     }
371
372     private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
373         buffer.position(0);
374         byte typeAndFlags = buffer.get(0);
375         // Shift the xTR-ID present and built for an RTR bits to their correct position
376         byte flags = (byte) ((typeAndFlags << 2) & 0x0F);
377         // Set control message type to 4 (Map-Notify)
378         byte type = 0x40;
379         // Combine the nibbles
380         typeAndFlags = (byte) (type | flags);
381         byte[] byteReplacement = new byte[] {typeAndFlags, 0x00, 0x00};
382         buffer.put(byteReplacement);
383
384         return buffer;
385     }
386
387     private List<EidLispAddress> provideEidPrefixesFromMessage(final MapRegister mapRegister) {
388         List<EidLispAddress> eidsResult = new ArrayList<>();
389         for (MappingRecordItem mappingRecordItem : mapRegister.getMappingRecordItem()) {
390             final EidLispAddressBuilder eidLispAddressBuilder = new EidLispAddressBuilder();
391             final Eid eid = mappingRecordItem.getMappingRecord().getEid();
392             eidLispAddressBuilder.setEidLispAddressId(LispAddressStringifier.getString(eid));
393             eidLispAddressBuilder.setEid(eid);
394             eidsResult.add(eidLispAddressBuilder.build());
395         }
396         return eidsResult;
397     }
398
399     /**
400      * Checks whether authentication data is valid.
401      *
402      * Methods pass through all records from map register message. For the EID of the first record it gets
403      * authentication key and does validation of authentication data again this authentication key. If it pass
404      * it just checks for remaining records (and its EID) whether they have the same authenticatin key stored in
405      * simple map cache (smc).
406      *
407      * @param mapRegister
408      * @param byteBuffer
409      * @return Returns authentication key if all of EIDs have the same authentication key or null otherwise
410      */
411     private MappingAuthkey tryToAuthenticateMessage(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
412         if (!authenticationEnabled) {
413             return null;
414         }
415
416         if (smc == null) {
417             LOG.debug("Simple map cache wasn't instantieted and set.");
418             return null;
419         }
420
421         MappingAuthkey firstAuthKey = null;
422         final List<MappingRecordItem> mappingRecords = mapRegister.getMappingRecordItem();
423         for (int i = 0; i < mappingRecords.size(); i++) {
424             final MappingRecordItem recordItem = mappingRecords.get(i);
425             final MappingRecord mappingRecord = recordItem.getMappingRecord();
426             if (i == 0) {
427                 firstAuthKey = smc.getAuthenticationKey(mappingRecord.getEid());
428                 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
429                     return null;
430                 }
431             } else {
432                 final Eid eid = mappingRecord.getEid();
433                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
434                 if (!firstAuthKey.equals(authKey)) {
435                     LOG.debug("Map register packet contained several eids. Authentication keys for first one and for " +
436                             "{} are different.",LispAddressStringifier.getString(eid));
437                     return null;
438                 }
439             }
440         }
441         return firstAuthKey;
442     }
443
444     private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
445         try {
446             MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
447             GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
448             gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
449             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
450             transportAddressBuilder.setIpAddress(LispNotificationHelper
451                     .getIpAddressBinaryFromInetAddress(sourceAddress));
452             transportAddressBuilder.setPort(new PortNumber(port));
453             gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
454             if (notificationPublishService != null) {
455                 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
456                 LOG.trace("MapNotify was published!");
457             } else {
458                 LOG.warn("Notification Provider is null!");
459             }
460         } catch (RuntimeException re) {
461             throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
462                     + inBuffer.capacity() + ")", re);
463         } catch (InterruptedException e) {
464             LOG.warn("Notification publication interrupted!");
465         }
466     }
467
468
469     private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
470         try {
471             MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
472             GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
473             gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
474             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
475             transportAddressBuilder.setIpAddress(LispNotificationHelper
476                     .getIpAddressBinaryFromInetAddress(sourceAddress));
477             transportAddressBuilder.setPort(new PortNumber(port));
478             gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
479             if (notificationPublishService != null) {
480                 notificationPublishService.putNotification(gotMapReplyBuilder.build());
481                 LOG.trace("MapReply was published!");
482             } else {
483                 LOG.warn("Notification Provider is null!");
484             }
485         } catch (RuntimeException re) {
486             throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
487                     + inBuffer.capacity() + ")", re);
488         } catch (InterruptedException e) {
489             LOG.warn("Notification publication interrupted!");
490         }
491     }
492
493     private void handleStats(int type) {
494         if (lispSbStats != null) {
495             if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
496                 lispSbStats.incrementRx(type);
497             } else {
498                 lispSbStats.incrementRxUnknown();
499             }
500         }
501     }
502
503     @Override
504     protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
505         if (LOG.isTraceEnabled()) {
506             LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
507                     msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
508         }
509         handlePacket(msg);
510     }
511
512     @Override
513     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
514         ctx.flush();
515     }
516
517     @Override
518     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
519         LOG.error("Error on channel: " + cause, cause);
520     }
521
522     @Override
523     public void close() throws Exception {
524         authenticationKeyDataListener.closeDataChangeListener();
525     }
526
527     public void setSimpleMapCache(final SimpleMapCache smc) {
528         this.smc = smc;
529     }
530
531     public void setDataBroker(final DataBroker dataBroker) {
532         this.dataBroker = dataBroker;
533     }
534
535     public void setNotificationProvider(NotificationPublishService nps) {
536         this.notificationPublishService = nps;
537     }
538
539     public void setMapRegisterCache(final MapRegisterCache mapRegisterCache) {
540         this.mapRegisterCache = mapRegisterCache;
541     }
542
543     public void setMapRegisterCacheEnabled(final boolean mapRegisterCacheEnabled) {
544         this.mapRegisterCacheEnabled = mapRegisterCacheEnabled;
545     }
546
547     /**
548     * Restore all keys from MDSAL datastore
549     */
550    public void restoreDaoFromDatastore() {
551        final List<AuthenticationKey> authKeys = dsbe.getAllAuthenticationKeys();
552        LOG.info("Restoring {} keys from datastore into southbound DAO", authKeys.size());
553
554        for (AuthenticationKey authKey : authKeys) {
555            final Eid key = authKey.getEid();
556            final MappingAuthkey mappingAuthkey = authKey.getMappingAuthkey();
557            LOG.debug("Adding authentication key '{}' with key-ID {} for {}", mappingAuthkey.getKeyString(),
558                    mappingAuthkey.getKeyType(),
559                    LispAddressStringifier.getString(key));
560            smc.addAuthenticationKey(key, mappingAuthkey);
561        }
562     }
563
564     public void init() {
565         Preconditions.checkNotNull(dataBroker);
566         Preconditions.checkNotNull(smc);
567         this.authenticationKeyDataListener = new AuthenticationKeyDataListener(dataBroker, smc);
568         dsbe = new DataStoreBackEnd(dataBroker);
569     }
570 }