Merge "Remove our NETCONF component"
[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 io.netty.buffer.ByteBufUtil;
12 import io.netty.channel.Channel;
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.config.ConfigIni;
27 import org.opendaylight.lispflowmapping.lisp.authentication.ILispAuthentication;
28 import org.opendaylight.lispflowmapping.lisp.authentication.LispAuthenticationUtil;
29 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
30 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
31 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
32 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
33 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
34 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
35 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
36 import org.opendaylight.lispflowmapping.lisp.util.MapRequestUtil;
37 import org.opendaylight.lispflowmapping.mapcache.AuthKeyDb;
38 import org.opendaylight.lispflowmapping.southbound.ConcurrentLispSouthboundStats;
39 import org.opendaylight.lispflowmapping.southbound.LispSouthboundPlugin;
40 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterCache;
41 import org.opendaylight.lispflowmapping.southbound.lisp.cache.MapRegisterPartialDeserializer;
42 import org.opendaylight.lispflowmapping.southbound.lisp.exception.LispMalformedPacketException;
43 import org.opendaylight.lispflowmapping.southbound.lisp.network.PacketHeader;
44 import org.opendaylight.lispflowmapping.southbound.util.LispNotificationHelper;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMappingBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotifyBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReplyBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAliveBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMappingBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.key.container.MapRegisterCacheKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadata;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.MapRegisterCacheMetadataBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddress;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.metadata.container.map.register.cache.metadata.EidLispAddressBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValue;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.map.register.cache.value.grouping.MapRegisterCacheValueBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
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.yangtools.yang.binding.Notification;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 @ChannelHandler.Sharable
74 public class LispSouthboundHandler extends SimpleChannelInboundHandler<DatagramPacket>
75         implements ILispSouthboundService, AutoCloseable {
76     private MapRegisterCache mapRegisterCache;
77     private long mapRegisterCacheTimeout;
78
79     private DataBroker dataBroker;
80     private NotificationPublishService notificationPublishService;
81
82     protected static final Logger LOG = LoggerFactory.getLogger(LispSouthboundHandler.class);
83
84     //TODO: think whether this field can be accessed through mappingservice or some other configuration parameter
85     private boolean authenticationEnabled = ConfigIni.getInstance().isAuthEnabled();
86     private final LispSouthboundPlugin lispSbPlugin;
87     private ConcurrentLispSouthboundStats lispSbStats = null;
88     private AuthKeyDb akdb;
89     private AuthenticationKeyDataListener authenticationKeyDataListener;
90     private boolean isReadFromChannelEnabled = true;
91
92     private Channel channel;
93
94     public LispSouthboundHandler(LispSouthboundPlugin lispSbPlugin) {
95         this.lispSbPlugin = lispSbPlugin;
96     }
97
98     public void handlePacket(DatagramPacket msg) {
99         ByteBuffer inBuffer = msg.content().nioBuffer();
100         int type = ByteUtil.getUnsignedByte(inBuffer, LispMessage.Pos.TYPE) >> 4;
101         handleStats(type);
102         Object lispType = MessageType.forValue(type);
103         if (lispType == MessageType.EncapsulatedControlMessage) {
104             LOG.trace("Received packet of type Encapsulated Control Message");
105             handleEncapsulatedControlMessage(inBuffer, msg.sender().getAddress());
106         } else if (lispType == MessageType.MapRequest) {
107             LOG.trace("Received packet of type Map-Request");
108             handleMapRequest(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
109         } else if (lispType == MessageType.MapRegister) {
110             LOG.trace("Received packet of type Map-Register");
111             handleMapRegister(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
112         } else if (lispType == MessageType.MapNotify) {
113             LOG.trace("Received packet of type Map-Notify");
114             handleMapNotify(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
115         } else if (lispType == MessageType.MapReply) {
116             LOG.trace("Received packet of type Map-Reply");
117             handleMapReply(inBuffer, msg.sender().getAddress(), msg.sender().getPort());
118         } else {
119             LOG.warn("Received unknown LISP control packet (type " + ((lispType != null) ? lispType : type) + ")");
120         }
121     }
122
123     @SuppressWarnings("checkstyle:IllegalCatch")
124     private void handleEncapsulatedControlMessage(ByteBuffer inBuffer, InetAddress sourceAddress) {
125         try {
126             handleMapRequest(inBuffer, sourceAddress, extractEncapsulatedSourcePort(inBuffer));
127         } catch (RuntimeException re) {
128             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
129                     + inBuffer.capacity() + ")", re);
130         }
131     }
132
133     @SuppressWarnings("checkstyle:IllegalCatch")
134     private void handleMapRequest(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
135         try {
136             MapRequest request = MapRequestSerializer.getInstance().deserialize(inBuffer, sourceAddress);
137             InetAddress finalSourceAddress = MapRequestUtil.selectItrRloc(request);
138             if (finalSourceAddress == null) {
139                 throw new LispMalformedPacketException("Couldn't deserialize Map-Request, no ITR Rloc found!");
140             }
141
142             RequestMappingBuilder requestMappingBuilder = new RequestMappingBuilder();
143             requestMappingBuilder.setMapRequest(LispNotificationHelper.convertMapRequest(request));
144             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
145             transportAddressBuilder.setIpAddress(
146                     LispNotificationHelper.getIpAddressBinaryFromInetAddress(finalSourceAddress));
147             transportAddressBuilder.setPort(new PortNumber(port));
148             requestMappingBuilder.setTransportAddress(transportAddressBuilder.build());
149             if (notificationPublishService != null) {
150                 notificationPublishService.putNotification(requestMappingBuilder.build());
151                 LOG.trace("MapRequest was published!");
152             } else {
153                 LOG.warn("Notification Provider is null!");
154             }
155         } catch (RuntimeException re) {
156             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
157                     + inBuffer.capacity() + ")", re);
158         } catch (InterruptedException e) {
159             LOG.warn("Notification publication interrupted!");
160         }
161     }
162
163     @SuppressWarnings("checkstyle:IllegalCatch")
164     private int extractEncapsulatedSourcePort(ByteBuffer inBuffer) {
165         try {
166             inBuffer.position(PacketHeader.Length.LISP_ENCAPSULATION);
167             int ipType = (inBuffer.get() >> 4);
168             if (ipType == 4) {
169                 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV4 - 1);
170             } else if (ipType == 6) {
171                 inBuffer.position(inBuffer.position() + PacketHeader.Length.IPV6_NO_EXT - 1);
172             } else {
173                 throw new LispMalformedPacketException(
174                         "Couldn't deserialize Map-Request: inner packet has unknown IP version: " + ipType);
175             }
176
177             int encapsulatedSourcePort = inBuffer.getShort() & 0xFFFF;
178             inBuffer.position(inBuffer.position() + PacketHeader.Length.UDP - 2);
179             return encapsulatedSourcePort;
180         } catch (RuntimeException re) {
181             throw new LispMalformedPacketException("Couldn't deserialize Map-Request (len="
182                     + inBuffer.capacity() + ")", re);
183         }
184     }
185
186     @SuppressWarnings("checkstyle:IllegalCatch")
187     private void handleMapRegister(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
188         try {
189             Map.Entry<MapRegisterCacheKey, byte[]> artificialEntry = null;
190             MapRegisterCacheKey cacheKey = null;
191             MapRegisterCacheValue cacheValue = null;
192             if (lispSbPlugin.isMapRegisterCacheEnabled()) {
193                 artificialEntry = MapRegisterPartialDeserializer.deserializePartially(inBuffer, sourceAddress);
194                 cacheKey = artificialEntry == null ? null : artificialEntry.getKey();
195                 cacheValue = resolveCacheValue(artificialEntry);
196             }
197             if (cacheValue != null) {
198                 lispSbStats.incrementCacheHits();
199                 MapRegisterCacheMetadata mapRegisterMeta = cacheValue.getMapRegisterCacheMetadata();
200                 LOG.debug("Map register message site-ID: {} xTR-ID: {} from cache.", mapRegisterMeta.getSiteId(),
201                         mapRegisterMeta.getXtrId());
202                 cacheValue = refreshEntry(cacheKey);
203                 if (cacheValue != null) {
204                     sendNotificationIfPossible(createMappingKeepAlive(cacheValue));
205                     if (cacheValue.getMapRegisterCacheMetadata().isWantMapNotify()) {
206                         sendMapNotifyMsg(inBuffer, sourceAddress, port, cacheValue);
207                     }
208                 }
209             } else {
210                 lispSbStats.incrementCacheMisses();
211                 MapRegister mapRegister = MapRegisterSerializer.getInstance().deserialize(inBuffer, sourceAddress);
212
213                 MappingAuthkey mappingAuthkey = null;
214                 if (authenticationEnabled) {
215                     mappingAuthkey = tryToAuthenticateMessage(mapRegister, inBuffer);
216                     if (mappingAuthkey == null) {
217                         return;
218                     }
219                 }
220
221                 AddMappingBuilder addMappingBuilder = new AddMappingBuilder();
222                 addMappingBuilder.setMapRegister(LispNotificationHelper.convertMapRegister(mapRegister));
223                 TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
224                 transportAddressBuilder.setIpAddress(LispNotificationHelper.getIpAddressBinaryFromInetAddress(
225                         sourceAddress));
226                 transportAddressBuilder.setPort(new PortNumber(port));
227                 addMappingBuilder.setTransportAddress(transportAddressBuilder.build());
228                 sendNotificationIfPossible(addMappingBuilder.build());
229                 if (artificialEntry != null) {
230                     final MapRegisterCacheMetadataBuilder cacheMetadataBldNew = new
231                             MapRegisterCacheMetadataBuilder();
232                     cacheMetadataBldNew.setEidLispAddress(provideEidPrefixesFromMessage(mapRegister));
233                     cacheMetadataBldNew.setXtrId(mapRegister.getXtrId());
234                     cacheMetadataBldNew.setSiteId(mapRegister.getSiteId());
235                     cacheMetadataBldNew.setWantMapNotify(mapRegister.isWantMapNotify());
236                     cacheMetadataBldNew.setMergeEnabled(mapRegister.isMergeEnabled());
237                     cacheMetadataBldNew.setTimestamp(System.currentTimeMillis());
238
239                     final MapRegisterCacheValueBuilder cacheValueBldNew = new MapRegisterCacheValueBuilder();
240                     cacheValueBldNew.setPacketData(artificialEntry.getValue());
241                     cacheValueBldNew.setMappingAuthkey(mappingAuthkey);
242                     cacheValueBldNew.setMapRegisterCacheMetadata(cacheMetadataBldNew.build());
243
244                     mapRegisterCache.addEntry(cacheKey, cacheValueBldNew.build());
245                 }
246             }
247         } catch (RuntimeException re) {
248             throw new LispMalformedPacketException("Couldn't deserialize Map-Register (len="
249                     + inBuffer.capacity() + ")", re);
250         } catch (InterruptedException e) {
251             LOG.warn("Notification publication interrupted!");
252         }
253     }
254
255     private MapRegisterCacheValue refreshEntry(final MapRegisterCacheKey cacheKey) {
256         MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.refreshEntry(cacheKey);
257         if (mapRegisterCacheValue != null) {
258             mapRegisterCacheValue = refreshAuthKeyIfNecessary(mapRegisterCacheValue);
259             mapRegisterCache.addEntry(cacheKey, mapRegisterCacheValue);
260             return mapRegisterCacheValue;
261         }
262         return null;
263     }
264
265     private MapRegisterCacheValue refreshAuthKeyIfNecessary(MapRegisterCacheValue mapRegisterCacheValue) {
266         if (authenticationKeyDataListener.isAuthKeyRefreshing()) {
267             final boolean shouldAuthKeyRefreshingStop = System.currentTimeMillis() - authenticationKeyDataListener
268                     .getAuthKeyRefreshingDate() > mapRegisterCacheTimeout;
269             if (shouldAuthKeyRefreshingStop) {
270                 authenticationKeyDataListener.setAuthKeyRefreshing(false);
271             } else {
272                 final MappingAuthkey mappingAuthkey = provideAuthenticateKey(mapRegisterCacheValue
273                         .getMapRegisterCacheMetadata().getEidLispAddress());
274
275                 final MapRegisterCacheValueBuilder newMapRegisterCacheValueBuilder = new MapRegisterCacheValueBuilder(
276                         mapRegisterCacheValue);
277                 final MapRegisterCacheMetadataBuilder newMapRegisterCacheMetadataBuilder =
278                         new MapRegisterCacheMetadataBuilder(mapRegisterCacheValue.getMapRegisterCacheMetadata());
279
280                 newMapRegisterCacheValueBuilder.setMappingAuthkey(mappingAuthkey);
281                 newMapRegisterCacheValueBuilder.setMapRegisterCacheMetadata(newMapRegisterCacheMetadataBuilder.build());
282                 return newMapRegisterCacheValueBuilder.build();
283             }
284         }
285
286         return mapRegisterCacheValue;
287
288     }
289
290     private MapRegisterCacheValue resolveCacheValue(Map.Entry<MapRegisterCacheKey, byte[]> entry) {
291         if (entry != null) {
292             final MapRegisterCacheValue mapRegisterCacheValue = mapRegisterCache.getEntry(entry.getKey());
293             if (mapRegisterCacheValue != null) {
294                 final long creationTime = mapRegisterCacheValue.getMapRegisterCacheMetadata().getTimestamp();
295                 final long currentTime = System.currentTimeMillis();
296                 if (currentTime - creationTime > mapRegisterCacheTimeout) {
297                     mapRegisterCache.removeEntry(entry.getKey());
298                     return null;
299                 } else if (Arrays.equals(mapRegisterCacheValue.getPacketData(), entry.getValue())) {
300                     return mapRegisterCacheValue;
301                 }
302             }
303         }
304         return null;
305     }
306
307     private void sendNotificationIfPossible(final Notification notification) throws InterruptedException {
308         if (notificationPublishService != null) {
309             notificationPublishService.putNotification(notification);
310             LOG.trace("{} was published.", notification.getClass());
311         } else {
312             LOG.warn("Notification Provider is null!");
313         }
314     }
315
316     private MappingKeepAlive createMappingKeepAlive(final MapRegisterCacheValue value) {
317         MappingKeepAliveBuilder mappingKeepAliveBuilder = new MappingKeepAliveBuilder();
318         mappingKeepAliveBuilder.setMapRegisterCacheMetadata(value.getMapRegisterCacheMetadata());
319         return mappingKeepAliveBuilder.build();
320     }
321
322     /**
323      * Returns null if not all of eids have the same value of authentication key.
324      */
325     private MappingAuthkey provideAuthenticateKey(final List<EidLispAddress> eidLispAddresses) {
326         MappingAuthkey firstAuthKey = null;
327         for (int i = 0; i < eidLispAddresses.size(); i++) {
328             final Eid eid = eidLispAddresses.get(i).getEid();
329             if (i == 0) {
330                 firstAuthKey = akdb.getAuthenticationKey(eid);
331             } else {
332                 final MappingAuthkey authKey = akdb.getAuthenticationKey(eid);
333                 if (!Objects.equals(firstAuthKey, authKey)) {
334                     return null;
335                 }
336             }
337         }
338         return firstAuthKey;
339
340     }
341
342     private void sendMapNotifyMsg(final ByteBuffer inBuffer, final InetAddress inetAddress, int portNumber,
343                                   MapRegisterCacheValue mapRegisterValue) {
344         if (mapRegisterValue.getMappingAuthkey().getKeyType() != null) {
345             ByteBuffer outBuffer = transformMapRegisterToMapNotify(inBuffer);
346             if (mapRegisterValue.getMappingAuthkey().getKeyType() != 0) {
347                 outBuffer = calculateAndSetNewMAC(outBuffer, mapRegisterValue.getMappingAuthkey().getKeyString());
348             }
349             outBuffer.position(0);
350             lispSbPlugin.handleSerializedLispBuffer(inetAddress, outBuffer, MessageType.MapNotify, portNumber,
351                     this.channel);
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      * the authentication key database (akdb).
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 (akdb == null) {
406             LOG.debug("Simple map cache wasn't instantieted and set.");
407             return null;
408         }
409
410         MappingAuthkey firstAuthKey = null;
411         final List<MappingRecordItem> mappingRecords = mapRegister.getMappingRecordItem();
412         for (int i = 0; i < mappingRecords.size(); i++) {
413             final MappingRecordItem recordItem = mappingRecords.get(i);
414             final MappingRecord mappingRecord = recordItem.getMappingRecord();
415             if (i == 0) {
416                 firstAuthKey = akdb.getAuthenticationKey(mappingRecord.getEid());
417                 if (!LispAuthenticationUtil.validate(mapRegister, byteBuffer, mappingRecord.getEid(), firstAuthKey)) {
418                     return null;
419                 }
420             } else {
421                 final Eid eid = mappingRecord.getEid();
422                 final MappingAuthkey authKey = akdb.getAuthenticationKey(eid);
423                 if (!firstAuthKey.equals(authKey)) {
424                     LOG.debug("Map register packet contained several eids. Authentication keys for first one and for "
425                             + "{} are different.",LispAddressStringifier.getString(eid));
426                     return null;
427                 }
428             }
429         }
430         return firstAuthKey;
431     }
432
433     @SuppressWarnings("checkstyle:IllegalCatch")
434     private void handleMapNotify(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
435         try {
436             MapNotify mapNotify = MapNotifySerializer.getInstance().deserialize(inBuffer);
437             GotMapNotifyBuilder gotMapNotifyBuilder = new GotMapNotifyBuilder();
438             gotMapNotifyBuilder.setMapNotify(LispNotificationHelper.convertMapNotify(mapNotify));
439             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
440             transportAddressBuilder.setIpAddress(LispNotificationHelper
441                     .getIpAddressBinaryFromInetAddress(sourceAddress));
442             transportAddressBuilder.setPort(new PortNumber(port));
443             gotMapNotifyBuilder.setTransportAddress(transportAddressBuilder.build());
444             if (notificationPublishService != null) {
445                 notificationPublishService.putNotification(gotMapNotifyBuilder.build());
446                 LOG.trace("MapNotify was published!");
447             } else {
448                 LOG.warn("Notification Provider is null!");
449             }
450         } catch (RuntimeException re) {
451             throw new LispMalformedPacketException("Couldn't deserialize Map-Notify (len="
452                     + inBuffer.capacity() + ")", re);
453         } catch (InterruptedException e) {
454             LOG.warn("Notification publication interrupted!");
455         }
456     }
457
458     @SuppressWarnings("checkstyle:IllegalCatch")
459     private void handleMapReply(ByteBuffer inBuffer, InetAddress sourceAddress, int port) {
460         try {
461             MapReply mapReply = MapReplySerializer.getInstance().deserialize(inBuffer);
462             GotMapReplyBuilder gotMapReplyBuilder = new GotMapReplyBuilder();
463             gotMapReplyBuilder.setMapReply(LispNotificationHelper.convertMapReply(mapReply));
464             TransportAddressBuilder transportAddressBuilder = new TransportAddressBuilder();
465             transportAddressBuilder.setIpAddress(LispNotificationHelper
466                     .getIpAddressBinaryFromInetAddress(sourceAddress));
467             transportAddressBuilder.setPort(new PortNumber(port));
468             gotMapReplyBuilder.setTransportAddress(transportAddressBuilder.build());
469             if (notificationPublishService != null) {
470                 notificationPublishService.putNotification(gotMapReplyBuilder.build());
471                 LOG.trace("MapReply was published!");
472             } else {
473                 LOG.warn("Notification Provider is null!");
474             }
475         } catch (RuntimeException re) {
476             throw new LispMalformedPacketException("Couldn't deserialize Map-Reply (len="
477                     + inBuffer.capacity() + ")", re);
478         } catch (InterruptedException e) {
479             LOG.warn("Notification publication interrupted!");
480         }
481     }
482
483     private void handleStats(int type) {
484         if (lispSbStats != null) {
485             if (type <= ConcurrentLispSouthboundStats.MAX_LISP_TYPES) {
486                 lispSbStats.incrementRx(type);
487             } else {
488                 lispSbStats.incrementRxUnknown();
489             }
490         }
491     }
492
493     @Override
494     protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
495         if (isReadFromChannelEnabled) {
496             if (LOG.isTraceEnabled()) {
497                 LOG.trace("Received UDP packet from {}:{} with content:\n{}", msg.sender().getHostString(),
498                         msg.sender().getPort(), ByteBufUtil.prettyHexDump(msg.content()));
499             }
500             this.channel = ctx.channel();
501             handlePacket(msg);
502         }
503     }
504
505     @Override
506     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
507         ctx.flush();
508     }
509
510     @Override
511     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
512         LOG.error("Error on channel: " + cause, cause);
513     }
514
515     @Override
516     public void close() throws Exception {
517     }
518
519     public void setAuthKeyDb(final AuthKeyDb smc) {
520         this.akdb = smc;
521     }
522
523     public void setDataBroker(final DataBroker dataBroker) {
524         this.dataBroker = dataBroker;
525     }
526
527     public void setNotificationProvider(NotificationPublishService nps) {
528         this.notificationPublishService = nps;
529     }
530
531     public void setMapRegisterCache(final MapRegisterCache mapRegisterCache) {
532         this.mapRegisterCache = mapRegisterCache;
533     }
534
535     public void setAuthenticationKeyDataListener(AuthenticationKeyDataListener authenticationKeyDataListener) {
536         this.authenticationKeyDataListener = authenticationKeyDataListener;
537     }
538
539     public void setStats(ConcurrentLispSouthboundStats lispSbStats) {
540         this.lispSbStats = lispSbStats;
541     }
542
543     public void setIsMaster(boolean isReadFromChannelEnabled) {
544         this.isReadFromChannelEnabled = isReadFromChannelEnabled;
545     }
546
547     public void setMapRegisterCacheTimeout(long mapRegisterCacheTimeout) {
548         this.mapRegisterCacheTimeout = mapRegisterCacheTimeout;
549     }
550 }