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