3bdbe904bc82c245465ce1baec88c5417652681c
[lispflowmapping.git] / mappingservice / implementation / src / main / java / org / opendaylight / lispflowmapping / implementation / lisp / MapServer.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.implementation.lisp;
10
11 import java.net.InetAddress;
12 import java.net.NetworkInterface;
13 import java.net.SocketException;
14 import java.util.ArrayList;
15 import java.util.Enumeration;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Random;
20 import java.util.Map.Entry;
21 import java.util.Set;
22
23 import org.apache.commons.lang3.BooleanUtils;
24 import org.apache.commons.lang3.exception.ExceptionUtils;
25 import org.opendaylight.lispflowmapping.implementation.authentication.LispAuthenticationUtil;
26 import org.opendaylight.lispflowmapping.implementation.config.ConfigIni;
27 import org.opendaylight.lispflowmapping.implementation.dao.MappingServiceKeyUtil;
28 import org.opendaylight.lispflowmapping.implementation.util.DAOMappingUtil;
29 import org.opendaylight.lispflowmapping.implementation.util.LispAFIConvertor;
30 import org.opendaylight.lispflowmapping.implementation.util.MapNotifyBuilderHelper;
31 import org.opendaylight.lispflowmapping.inmemorydb.HashMapDb;
32 import org.opendaylight.lispflowmapping.implementation.util.MaskUtil;
33 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
34 import org.opendaylight.lispflowmapping.interfaces.dao.IMappingServiceKey;
35 import org.opendaylight.lispflowmapping.interfaces.dao.MappingEntry;
36 import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceRLOCGroup;
37 import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceSubscriberRLOC;
38 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
39 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.LispAFIAddress;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRegister;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidrecords.EidRecordBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidtolocatorrecords.EidToLocatorRecord;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidtolocatorrecords.EidToLocatorRecordBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.LispAddressContainer;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.Address;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.LcafKeyValue;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispaddress.lispaddresscontainer.address.LcafSourceDest;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.lispsimpleaddress.primitiveaddress.DistinguishedName;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.locatorrecords.LocatorRecord;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.mapnotifymessage.MapNotifyBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.ItrRloc;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.ItrRlocBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequest.SourceEidBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.maprequestnotification.MapRequestBuilder;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class MapServer extends AbstractLispComponent implements IMapServerAsync {
60
61     protected static final Logger LOG = LoggerFactory.getLogger(MapServer.class);
62
63     private static final ConfigIni configIni = new ConfigIni();
64     private static final boolean overwriteConfig = configIni.mappingOverwriteIsSet();
65     private boolean overwrite;
66
67     public MapServer(ILispDAO dao) {
68         this(dao, overwriteConfig);
69     }
70
71     public MapServer(ILispDAO dao, boolean overwrite) {
72         this(dao, overwrite, true);
73     }
74
75     public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate) {
76         this(dao, overwrite, authenticate, true);
77     }
78
79     public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate, boolean iterateAuthenticationMask) {
80         super(dao, authenticate, iterateAuthenticationMask);
81         this.overwrite = overwrite;
82     }
83
84     private static InetAddress getLocalAddress() {
85         try {
86             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
87             while (interfaces.hasMoreElements()) {
88                 NetworkInterface current = interfaces.nextElement();
89                 LOG.debug("Interface " + current.toString());
90                 if (!current.isUp() || current.isLoopback() || current.isVirtual())
91                     continue;
92                 Enumeration<InetAddress> addresses = current.getInetAddresses();
93                 while (addresses.hasMoreElements()) {
94                     InetAddress current_addr = addresses.nextElement();
95                     // Skip loopback and link local addresses
96                     if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress())
97                         continue;
98                     LOG.debug(current_addr.getHostAddress());
99                     return current_addr;
100                 }
101             }
102         } catch (SocketException se) {
103         }
104         return null;
105     }
106
107     private static MapRequestBuilder buildSMR(LispAddressContainer srcEid) {
108         MapRequestBuilder builder = new MapRequestBuilder();
109         builder.setAuthoritative(false);
110         builder.setMapDataPresent(false);
111         builder.setPitr(false);
112         builder.setProbe(false);
113         builder.setSmr(true);
114         builder.setSmrInvoked(false);
115
116         builder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(srcEid).build());
117         builder.setItrRloc(new ArrayList<ItrRloc>());
118         builder.getItrRloc().add(new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(getLocalAddress())).build());
119         builder.setMapReply(null);
120         builder.setNonce(new Random().nextLong());
121
122         return builder;
123     }
124
125     public void handleMapRegister(MapRegister mapRegister, boolean smr, IMapNotifyHandler callback) {
126         if (dao == null) {
127             LOG.warn("handleMapRegister called while dao is uninitialized");
128         } else {
129             boolean failed = false;
130             String password = null;
131             for (EidToLocatorRecord eidRecord : mapRegister.getEidToLocatorRecord()) {
132                 if (shouldAuthenticate()) {
133                     password = getPassword(eidRecord.getLispAddressContainer(), eidRecord.getMaskLength());
134                     if (!LispAuthenticationUtil.validate(mapRegister, password)) {
135                         LOG.warn("Authentication failed");
136                         failed = true;
137                         break;
138                     }
139                 }
140                 boolean mappingChanged = saveRlocs(eidRecord, smr);
141                 if (smr && mappingChanged) {
142                     sendSmrs(eidRecord, callback);
143                 }
144             }
145             if (!failed) {
146                 MapNotifyBuilder builder = new MapNotifyBuilder();
147                 if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
148                     LOG.trace("MapRegister wants MapNotify");
149                     MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
150                     if (shouldAuthenticate()) {
151                         builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(), password));
152                     }
153                     callback.handleMapNotify(builder.build());
154                 }
155             }
156         }
157     }
158
159     public boolean saveRlocs(EidToLocatorRecord eidRecord, boolean checkForChanges) {
160         Map<String, MappingServiceRLOCGroup> rlocGroups = new HashMap<String, MappingServiceRLOCGroup>();
161         if (eidRecord.getLocatorRecord() != null) {
162             for (LocatorRecord locatorRecord : eidRecord.getLocatorRecord()) {
163                 String subkey = getAddressKey(locatorRecord.getLispAddressContainer().getAddress());
164                 if (!rlocGroups.containsKey(subkey)) {
165                     rlocGroups.put(subkey, new MappingServiceRLOCGroup(eidRecord.getRecordTtl(), eidRecord.getAction(), eidRecord.isAuthoritative()));
166                 }
167                 rlocGroups.get(subkey).addRecord(locatorRecord);
168             }
169         } else {
170             rlocGroups.put(ADDRESS_SUBKEY, new MappingServiceRLOCGroup(eidRecord.getRecordTtl(), eidRecord.getAction(), eidRecord.isAuthoritative()));
171         }
172         List<MappingEntry<MappingServiceRLOCGroup>> entries = new ArrayList<>();
173         for (String subkey : rlocGroups.keySet()) {
174             entries.add(new MappingEntry<>(subkey, rlocGroups.get(subkey)));
175         }
176
177         if (eidRecord.getLispAddressContainer().getAddress() instanceof LcafSourceDest) {
178             Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> oldMapping= null, newMapping = null;
179             LispAFIAddress srcAddr = getSrcForLcafSrcDst(eidRecord.getLispAddressContainer());
180             LispAFIAddress dstAddr = getDstForLcafSrcDst(eidRecord.getLispAddressContainer());
181             short srcMask = getSrcMaskForLcafSrcDst(eidRecord.getLispAddressContainer());
182             short dstMask = getDstMaskForLcafSrcDst(eidRecord.getLispAddressContainer());
183
184             if (checkForChanges) {
185                 oldMapping = DAOMappingUtil.getMappingExact(srcAddr, dstAddr, srcMask, dstMask, dao);
186             }
187             IMappingServiceKey dstKey = MappingServiceKeyUtil.generateMappingServiceKey(dstAddr, dstMask);
188             ILispDAO srcDstDao = (ILispDAO) dao.getSpecific(dstKey, LCAF_SRCDST_SUBKEY);
189             if (srcDstDao == null) {
190                 srcDstDao = new HashMapDb();
191                 dao.put(dstKey, new MappingEntry<>(LCAF_SRCDST_SUBKEY, srcDstDao));
192             }
193             IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(srcAddr, srcMask);
194             srcDstDao.put(srcKey, entries.toArray(new MappingEntry[entries.size()]));
195             if (checkForChanges) {
196                 newMapping = DAOMappingUtil.getMappingExact(srcAddr, dstAddr, srcMask, dstMask, dao);
197                 return (newMapping.getValue() == null) ? oldMapping.getValue() != null :
198                                                         !newMapping.getValue().equals(oldMapping.getValue());
199             }
200         } else {
201             List<MappingServiceRLOCGroup> oldLocators = null, newLocators = null;
202             if (checkForChanges) {
203                 oldLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
204             }
205             IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(eidRecord.getLispAddressContainer(),
206                     eidRecord.getMaskLength());
207             dao.put(key, entries.toArray(new MappingEntry[entries.size()]));
208             if (checkForChanges) {
209                 newLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
210                 return (newLocators == null) ? oldLocators != null : !newLocators.equals(oldLocators);
211             }
212         }
213         return false;
214     }
215
216     private String getAddressKey(Address address) {
217         if (address instanceof LcafKeyValue) {
218             LcafKeyValue keyVal = (LcafKeyValue) address;
219             if (keyVal.getLcafKeyValueAddressAddr().getKey().getPrimitiveAddress() instanceof DistinguishedName) {
220                 return ((DistinguishedName) keyVal.getLcafKeyValueAddressAddr().getKey().getPrimitiveAddress()).getDistinguishedNameAddress().getDistinguishedName();
221             }
222         }
223         if (shouldOverwrite()) {
224             return ADDRESS_SUBKEY;
225         } else {
226             return String.valueOf(address.hashCode());
227         }
228     }
229
230     public String getAuthenticationKey(LispAddressContainer address, int maskLen) {
231         return getPassword(address, maskLen);
232     }
233
234     public void removeAuthenticationKey(LispAddressContainer address, int maskLen) {
235         if (address.getAddress() instanceof LcafSourceDest) {
236             ILispDAO srcDstDao = getSrcDstInnerDao(address, maskLen);
237             if (srcDstDao != null) {
238                 IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(getSrcForLcafSrcDst(address),
239                         getSrcMaskForLcafSrcDst(address));
240                 srcDstDao.removeSpecific(srcKey, PASSWORD_SUBKEY);
241             }
242         } else {
243             IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
244             dao.removeSpecific(key, PASSWORD_SUBKEY);
245         }
246     }
247
248     public void addAuthenticationKey(LispAddressContainer address, int maskLen, String key) {
249         IMappingServiceKey mappingServiceKey = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
250         if (address.getAddress() instanceof LcafSourceDest) {
251             IMappingServiceKey srcKey = MappingServiceKeyUtil.generateMappingServiceKey(getSrcForLcafSrcDst(address),
252                     getSrcMaskForLcafSrcDst(address));
253             ILispDAO srcDstDao = getOrInstantiateSrcDstInnerDao(address, maskLen);
254             srcDstDao.put(srcKey, new MappingEntry<String>(PASSWORD_SUBKEY, key));
255         } else {
256             dao.put(mappingServiceKey, new MappingEntry<String>(PASSWORD_SUBKEY, key));
257         }
258     }
259
260     public void removeMapping(LispAddressContainer address, int maskLen, boolean smr, IMapNotifyHandler callback) {
261         Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping;
262         ILispDAO db;
263         if (address.getAddress() instanceof LcafSourceDest) {
264             db = getSrcDstInnerDao(address, maskLen);
265             LispAFIAddress srcAddr = getSrcForLcafSrcDst(address);
266             short srcMask = getSrcMaskForLcafSrcDst(address);
267             mapping = DAOMappingUtil.getMappingForEid(srcAddr, srcMask, db);
268         } else {
269             db = dao;
270             mapping = DAOMappingUtil.getMappingForEid(LispAFIConvertor.toAFI(address), maskLen, db);
271         }
272         if (smr) {
273             // mapping is removed before first SMR is sent to avoid inconsistent replies
274             removeMappingRlocs(mapping, db);
275             sendSmrs(new EidToLocatorRecordBuilder().setLispAddressContainer(address).
276                     setMaskLength((short) maskLen).build(), callback);
277             db.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
278         } else {
279             removeMappingRlocs(mapping, db);
280             db.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
281         }
282     }
283
284     private void removeMappingRlocs(Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping, ILispDAO db) {
285         if (mapping == null || mapping.getValue() == null) {
286             return;
287         }
288         for (MappingServiceRLOCGroup group : mapping.getValue()) {
289             for (LocatorRecord record : group.getRecords()) {
290                 db.removeSpecific(mapping.getKey(), getAddressKey(record.getLispAddressContainer().getAddress()));
291             }
292         }
293     }
294
295     private void sendSmrs(EidToLocatorRecord record, IMapNotifyHandler callback) {
296         LispAddressContainer eid = record.getLispAddressContainer();
297         Set<MappingServiceSubscriberRLOC> subscribers;
298
299         subscribers = getSubscribers(eid, record.getMaskLength());
300         handleSmr(record, subscribers, callback);
301
302         // For SrcDst LCAF also send SMRs to Dst prefix
303         if (eid.getAddress() instanceof LcafSourceDest) {
304             LispAddressContainer dstAddr = LispAFIConvertor.toContainer(getDstForLcafSrcDst(eid));
305             short dstMask = getDstMaskForLcafSrcDst(eid);
306             subscribers = getSubscribers(dstAddr, dstMask);
307             EidToLocatorRecord newRecord = new EidToLocatorRecordBuilder().setAction(record.getAction()).
308                     setAuthoritative(record.isAuthoritative()).setLocatorRecord(record.getLocatorRecord()).
309                     setMapVersion(record.getMapVersion()).setRecordTtl(record.getRecordTtl()).
310                     setLispAddressContainer(dstAddr).setMaskLength(dstMask).build();
311             handleSmr(newRecord, subscribers, callback);
312         }
313     }
314
315     private void handleSmr(EidToLocatorRecord record, Set<MappingServiceSubscriberRLOC> subscribers,
316             IMapNotifyHandler callback) {
317         if (subscribers == null) {
318             return;
319         }
320         MapRequestBuilder mrb = buildSMR(record.getLispAddressContainer());
321         LOG.trace("Built SMR packet: " + mrb.build().toString());
322         for (MappingServiceSubscriberRLOC subscriber : subscribers) {
323             if (subscriber.timedOut()) {
324                 LOG.trace("Lazy removing expired subscriber entry " + subscriber.toString());
325                 subscribers.remove(subscriber);
326             } else {
327                 try {
328                     // The address stored in the SMR's EID record is used as Source EID in the SMR-invoked Map-Request. To
329                     // ensure consistent behavior it is set to the value used to originally request a given mapping
330                     mrb.setEidRecord(new ArrayList<org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.eidrecords.EidRecord>());
331                     mrb.getEidRecord().add(new EidRecordBuilder()
332                                 .setMask((short)MaskUtil.getMaxMask(LispAFIConvertor.toAFI(subscriber.getSrcEid())))
333                                 .setLispAddressContainer(subscriber.getSrcEid()).build());
334                     callback.handleSMR(mrb.build(), subscriber.getSrcRloc());
335                 } catch (Exception e) {
336                     LOG.error("Errors encountered while handling SMR:" + ExceptionUtils.getStackTrace(e));
337                 }
338             }
339         }
340         IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(record.getLispAddressContainer(),
341                 record.getMaskLength());
342         dao.put(key, new MappingEntry<Set<MappingServiceSubscriberRLOC>>(SUBSCRIBERS_SUBKEY, subscribers));
343     }
344
345     public boolean shouldOverwrite() {
346         return overwrite;
347     }
348
349     public void setOverwrite(boolean overwrite) {
350         this.overwrite = overwrite;
351     }
352
353 }