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