Bug 6351 - Clustering rework.
[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.lisp.authentication.ILispAuthentication;
29 import org.opendaylight.lispflowmapping.lisp.authentication.LispAuthenticationUtil;
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.rev130715.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.authkey.container.MappingAuthkey;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.db.instance.AuthenticationKey;
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     private long mapRegisterCacheTimeout;
81
82     private DataBroker dataBroker;
83     private NotificationPublishService notificationPublishService;
84
85     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
86
87     //TODO: think whether this field can be accessed through mappingservice or some other configuration parameter
88     private boolean authenticationEnabled = true;
89     private final LispSouthboundPlugin lispSbPlugin;
90     private LispSouthboundStats lispSbStats = null;
91     private SimpleMapCache smc;
92     private AuthenticationKeyDataListener authenticationKeyDataListener;
93     private DataStoreBackEnd dsbe;
94     private boolean isReadFromChannelEnabled = true;
95
96     public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
97         this.lispSbPlugin = lispSbPlugin;
98         if (lispSbPlugin != null) {
99             this.lispSbStats = lispSbPlugin.getStats();
100         }
101         this.mapRegisterCache = new MapRegisterCache();
102         this.smc = new SimpleMapCache(new HashMapDb());
103     }
104
105     public void handlePacket(DatagramPacket msg) {
106         ByteBuffer inBuffer = msg.content().nioBuffer();
107         int type = ByteUtil.getUnsignedByte(inBuffer, LispMessage.Pos.TYPE) >> 4;
108         handleStats(type);
109         Object lispType = MessageType.forValue(type);
110         if (lispType == MessageType.EncapsulatedControlMessage) {
111             LOG.trace("Received packet of type Encapsulated Control Message");
112             handleEncapsulatedControlMessage(inBuffer, msg.sender().getAddress());
113         } else if (lispType == MessageType.MapRequest) {
114             LOG.trace("Received packet of type Map-Request");
115             handleMapRequest(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
116         } else if (lispType == MessageType.MapRegister) {
117             LOG.trace("Received packet of type Map-Register");
118             handleMapRegister(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
119         } else if (lispType == MessageType.MapNotify) {
120             LOG.trace("Received packet of type Map-Notify");
121             handleMapNotify(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
122         } else if (lispType == MessageType.MapReply) {
123             LOG.trace("Received packet of type Map-Reply");
124             handleMapReply(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
125         } else {
126             LOG.warn("Received unknown LISP control packet (type " + ((lispType != null) ? lispType : type) + ")");
127         }
128     }
129
130     @SuppressWarnings("checkstyle:IllegalCatch")
131     private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
132         try {
133             handleMapRequest(inBuffer, sourceAddress, extractEncapsulatedSourcePort(inBuffer));
134         } catch (RuntimeException re) {
135             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
136                     + inBuffer.capacity() + ")", re);
137         }
138     }
139
140     @SuppressWarnings("checkstyle:IllegalCatch")
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     @SuppressWarnings("checkstyle:IllegalCatch")
171     private int extractEncapsulatedSourcePort(ByteBuffer inBuffer) {
172         try {
173             inBuffer.position(PacketHeader.Length.LISP_ENCAPSULATION);
174             int ipType = (inBuffer.get() >> 4);
175             if (ipType == 4) {
176                 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV4 - 1);
177             } else if (ipType == 6) {
178                 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV6_NO_EXT - 1);
179             } else {
180                 throw new LispMalformedPacketException(
181                         "Couldn't deserialize Map-Request: inner packet has unknown IP version: " + ipType);
182             }
183
184             int encapsulatedSourcePort = inBuffer.getShort() & 0xFFFF;
185             inBuffer.position(inBuffer.position() + PacketHeader.Length.UDP - 2);
186             return encapsulatedSourcePort;
187         } catch (RuntimeException re) {
188             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
189                     + inBuffer.capacity() + ")", re);
190         }
191     }
192
193     @SuppressWarnings("checkstyle:IllegalCatch")
194     private void handleMapRegister(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
195         try {
196             Map.Entry<MapRegisterCacheKey, byte[]> artificialEntry = null;
197             MapRegisterCacheKey cacheKey = null;
198             MapRegisterCacheValue cacheValue = null;
199             if (mapRegisterCacheEnabled) {
200                 artificialEntry = MapRegisterPartialDeserializer.deserializePartially(inBuffer, sourceAddress);
201                 cacheKey = artificialEntry == null ? null : artificialEntry.getKey();
202                 cacheValue = resolveCacheValue(artificialEntry);
203             }
204             if (cacheValue != null) {
205                 MapRegisterCacheMetadata mapRegisterMeta = cacheValue.getMapRegisterCacheMetadata();
206                 LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterMeta.getSiteId(),
207                         mapRegisterMeta.getXtrId());
208                 cacheValue = refreshEntry(cacheKey);
209                 if (cacheValue != null) {
210                     sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
211                     if (cacheValue.getMapRegisterCacheMetadata().isWantMapNotify()) {
212                         sendMapNotifyMsg(inBuffer, sourceAddress, port, cacheValue);
213                     }
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.setMappingAuthkey(mappingAuthkey);
241                         cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
242
243                         mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
244                     }
245                 }
246                 lispSbStats.incrementCacheMisses();
247             }
248         } catch (RuntimeException re) {
249             throw new LispMalformedPacketException("Couldn't deserialize Map-Register (len="
250                     + inBuffer.capacity() + ")", re);
251         } catch (InterruptedException e) {
252             LOG.warn("Notification publication interrupted!");
253         }
254     }
255
256     private MapRegisterCacheValue refreshEntry(final MapRegisterCacheKey cacheKey) {
257         MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.refreshEntry(cacheKey);
258         if (mapRegisterCacheValue != null) {
259             mapRegisterCacheValue = refreshAuthKeyIfNecessary(mapRegisterCacheValue);
260             mapRegisterCache.addEntry(cacheKey, mapRegisterCacheValue);
261             return mapRegisterCacheValue;
262         }
263         return null;
264     }
265
266     private MapRegisterCacheValue refreshAuthKeyIfNecessary(MapRegisterCacheValue mapRegisterCacheValue) {
267         if (authenticationKeyDataListener.isAuthKeyRefreshing()) {
268             final boolean shouldAuthKeyRefreshingStop = System.currentTimeMillis() - authenticationKeyDataListener
269                     .getAuthKeyRefreshingDate() > mapRegisterCacheTimeout;
270             if (shouldAuthKeyRefreshingStop) {
271                 authenticationKeyDataListener.setAuthKeyRefreshing(false);
272             } else {
273                 final MappingAuthkey mappingAuthkey = provideAuthenticateKey(mapRegisterCacheValue
274                         .getMapRegisterCacheMetadata().getEidLispAddress());
275
276                 final MapRegisterCacheValueBuilder newMapRegisterCacheValueBuilder = new MapRegisterCacheValueBuilder(
277                         mapRegisterCacheValue);
278                 final MapRegisterCacheMetadataBuilder newMapRegisterCacheMetadataBuilder =
279                         new MapRegisterCacheMetadataBuilder(mapRegisterCacheValue.getMapRegisterCacheMetadata());
280
281                 newMapRegisterCacheValueBuilder.setMappingAuthkey(mappingAuthkey);
282                 newMapRegisterCacheValueBuilder.setMapRegisterCacheMetadata(newMapRegisterCacheMetadataBuilder.build());
283                 return newMapRegisterCacheValueBuilder.build();
284             }
285         }
286
287         return mapRegisterCacheValue;
288
289     }
290
291     private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
292         if (entry != null) {
293             final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
294             if (mapRegisterCacheValue != null) {
295                 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
296                 final long currentTime = System.currentTimeMillis();
297                 if (currentTime - creationTime > mapRegisterCacheTimeout) {
298                     mapRegisterCache.removeEntry(entry.getKey());
299                     return null;
300                 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
301                     return mapRegisterCacheValue;
302                 }
303             }
304         }
305         return null;
306     }
307
308     private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
309         if (notificationPublishService != null) {
310             notificationPublishService.putNotification(notification);
311             LOG.trace("{} was published.", notification.getClass());
312         } else {
313             LOG.warn("Notification Provider is null!");
314         }
315     }
316
317     private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
318         MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
319         mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
320         return mappingKeepAliveBuilder.build();
321     }
322
323     /**
324      * Returns null if not all of eids have the same value of authentication key.
325      */
326     private MappingAuthkey provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
327         MappingAuthkey firstAuthKey = null;
328         for (int i = 0; i < eidLispAddresses.size(); i++) {
329             final Eid eid = eidLispAddresses.get(i).getEid();
330             if (i == 0) {
331                 firstAuthKey = smc.getAuthenticationKey(eid);
332             } else {
333                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
334                 if (!Objects.equals(firstAuthKey, authKey)) {
335                     return null;
336                 }
337             }
338         }
339         return firstAuthKey;
340
341     }
342
343     private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber,
344                                   MapRegisterCacheValue mapRegisterValue) {
345         if (mapRegisterValue.getMappingAuthkey().getKeyType() != null) {
346             ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
347             if (mapRegisterValue.getMappingAuthkey().getKeyType() != 0) {
348                 outBuffer = calculateAndSetNewMAC(outBuffer, mapRegisterValue.getMappingAuthkey().getKeyString());
349             }
350             outBuffer.position(0);
351             lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber);
352         } else {
353             LOG.error("Map-Register Cache: authentication succeeded, but can't find auth key for sending Map-Notify");
354         }
355     }
356
357     /**
358      * Calculates new message authentication code (MAC) for notify message.
359      */
360     private ByteBuffer calculateAndSetNewMAC(final ByteBuffer buffer, final String authKey) {
361         final byte[] authenticationData = LispAuthenticationUtil.createAuthenticationData(buffer, authKey);
362         buffer.position(ILispAuthentication.MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
363         buffer.put(authenticationData);
364         return buffer;
365     }
366
367     private ByteBuffer transformMapRegisterToMapNotify(final ByteBuffer buffer) {
368         buffer.position(0);
369         byte typeAndFlags = buffer.get(0);
370         // Shift the xTR-ID present and built for an RTR bits to their correct position
371         byte flags = (byte) ((typeAndFlags << 2) & 0x0F);
372         // Set control message type to 4 (Map-Notify)
373         byte type = 0x40;
374         // Combine the nibbles
375         typeAndFlags = (byte) (type | flags);
376         byte[] byteReplacement = new byte[] {typeAndFlags, 0x00, 0x00};
377         buffer.put(byteReplacement);
378
379         return buffer;
380     }
381
382     private List<EidLispAddress> provideEidPrefixesFromMessage(final MapRegister mapRegister) {
383         List<EidLispAddress> eidsResult = new ArrayList<>();
384         for (MappingRecordItem mappingRecordItem : mapRegister.getMappingRecordItem()) {
385             final EidLispAddressBuilder eidLispAddressBuilder = new EidLispAddressBuilder();
386             final Eid eid = mappingRecordItem.getMappingRecord().getEid();
387             eidLispAddressBuilder.setEidLispAddressId(LispAddressStringifier.getString(eid));
388             eidLispAddressBuilder.setEid(eid);
389             eidsResult.add(eidLispAddressBuilder.build());
390         }
391         return eidsResult;
392     }
393
394     /**
395      * Checks whether authentication data is valid.
396      *
397      * <p>Methods pass through all records from map register message. For the EID of the first record it gets
398      * authentication key and does validation of authentication data again this authentication key. If it pass
399      * it just checks for remaining records (and its EID) whether they have the same authenticatin key stored in
400      * simple map cache (smc).
401      *
402      * @return Returns authentication key if all of EIDs have the same authentication key or null otherwise
403      */
404     private MappingAuthkey tryToAuthenticateMessage(final MapRegister mapRegister, final ByteBuffer byteBuffer) {
405         if (!authenticationEnabled) {
406             return null;
407         }
408
409         if (smc == null) {
410             LOG.debug("Simple map cache wasn't instantieted and set.");
411             return null;
412         }
413
414         MappingAuthkey firstAuthKey = null;
415         final List<MappingRecordItem> mappingRecords = mapRegister.getMappingRecordItem();
416         for (int i = 0; i < mappingRecords.size(); i++) {
417             final MappingRecordItem recordItem = mappingRecords.get(i);
418             final MappingRecord mappingRecord = recordItem.getMappingRecord();
419             if (i == 0) {
420                 firstAuthKey = smc.getAuthenticationKey(mappingRecord.getEid());
421                 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
422                     return null;
423                 }
424             } else {
425                 final Eid eid = mappingRecord.getEid();
426                 final MappingAuthkey authKey = smc.getAuthenticationKey(eid);
427                 if (!firstAuthKey.equals(authKey)) {
428                     LOG.debug("Map register packet contained several eids. Authentication keys for first one and for "
429                             + "{} are different.",LispAddressStringifier.getString(eid));
430                     return null;
431                 }
432             }
433         }
434         return firstAuthKey;
435     }
436
437     @SuppressWarnings("checkstyle:IllegalCatch")
438     private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
439         try {
440             MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
441             GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
442             gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
443             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
444             transportAddressBuilder.setIpAddress(LispNotificationHelper
445                     .getIpAddressBinaryFromInetAddress(sourceAddress));
446             transportAddressBuilder.setPort(new PortNumber(port));
447             gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
448             if (notificationPublishService != null) {
449                 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
450                 LOG.trace("MapNotify was published!");
451             } else {
452                 LOG.warn("Notification Provider is null!");
453             }
454         } catch (RuntimeException re) {
455             throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
456                     + inBuffer.capacity() + ")", re);
457         } catch (InterruptedException e) {
458             LOG.warn("Notification publication interrupted!");
459         }
460     }
461
462     @SuppressWarnings("checkstyle:IllegalCatch")
463     private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
464         try {
465             MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
466             GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
467             gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
468             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
469             transportAddressBuilder.setIpAddress(LispNotificationHelper
470                     .getIpAddressBinaryFromInetAddress(sourceAddress));
471             transportAddressBuilder.setPort(new PortNumber(port));
472             gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
473             if (notificationPublishService != null) {
474                 notificationPublishService.putNotification(gotMapReplyBuilder.build());
475                 LOG.trace("MapReply was published!");
476             } else {
477                 LOG.warn("Notification Provider is null!");
478             }
479         } catch (RuntimeException re) {
480             throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
481                     + inBuffer.capacity() + ")", re);
482         } catch (InterruptedException e) {
483             LOG.warn("Notification publication interrupted!");
484         }
485     }
486
487     private void handleStats(int type) {
488         if (lispSbStats != null) {
489             if (type <= LispSouthboundStats.MAX_LISP_TYPES) {
490                 lispSbStats.incrementRx(type);
491             } else {
492                 lispSbStats.incrementRxUnknown();
493             }
494         }
495     }
496
497     @Override
498     protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
499         if (isReadFromChannelEnabled) {
500             if (LOG.isTraceEnabled()) {
501                 LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
502                         msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
503             }
504             handlePacket(msg);
505         }
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 setIsMaster(boolean isReadFromChannelEnabled) {
568         this.isReadFromChannelEnabled = isReadFromChannelEnabled;
569     }
570
571     public void setMapRegisterCacheTimeout(long mapRegisterCacheTimeout) {
572         this.mapRegisterCacheTimeout = mapRegisterCacheTimeout;
573     }
574 }