001ef709e22187a92c20bac6ed6201766a0846fb
[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.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Random;
21 import java.util.Map.Entry;
22
23 import org.apache.commons.lang3.BooleanUtils;
24 import org.opendaylight.lispflowmapping.implementation.authentication.LispAuthenticationUtil;
25 import org.opendaylight.lispflowmapping.implementation.config.ConfigIni;
26 import org.opendaylight.lispflowmapping.implementation.dao.MappingServiceKeyUtil;
27 import org.opendaylight.lispflowmapping.implementation.util.DAOMappingUtil;
28 import org.opendaylight.lispflowmapping.implementation.util.LispAFIConvertor;
29 import org.opendaylight.lispflowmapping.implementation.util.MapNotifyBuilderHelper;
30 import org.opendaylight.lispflowmapping.interfaces.dao.ILispDAO;
31 import org.opendaylight.lispflowmapping.interfaces.dao.IMappingServiceKey;
32 import org.opendaylight.lispflowmapping.interfaces.dao.MappingEntry;
33 import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceRLOCGroup;
34 import org.opendaylight.lispflowmapping.interfaces.dao.MappingServiceSubscriberRLOC;
35 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapNotifyHandler;
36 import org.opendaylight.lispflowmapping.interfaces.lisp.IMapServerAsync;
37 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapRegister;
38 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.MapRequest;
39 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidrecords.EidRecord;
40 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidrecords.EidRecordBuilder;
41 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidtolocatorrecords.EidToLocatorRecord;
42 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidtolocatorrecords.EidToLocatorRecordBuilder;
43 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.LispAddressContainer;
44 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.Address;
45 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispaddress.lispaddresscontainer.address.LcafKeyValue;
46 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.lispsimpleaddress.primitiveaddress.DistinguishedName;
47 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.locatorrecords.LocatorRecord;
48 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.mapnotifymessage.MapNotifyBuilder;
49 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequest.ItrRloc;
50 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequest.ItrRlocBuilder;
51 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequest.SourceEidBuilder;
52 import org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.maprequestnotification.MapRequestBuilder;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 public class MapServer extends AbstractLispComponent implements IMapServerAsync {
57
58     protected static final Logger LOG = LoggerFactory.getLogger(MapServer.class);
59
60     private static final ConfigIni configIni = new ConfigIni();
61     private static final boolean overwriteConfig = configIni.mappingOverwriteIsSet();
62     private boolean overwrite;
63
64     public MapServer(ILispDAO dao) {
65         this(dao, overwriteConfig);
66     }
67
68     public MapServer(ILispDAO dao, boolean overwrite) {
69         this(dao, overwrite, true);
70     }
71
72     public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate) {
73         this(dao, overwrite, authenticate, true);
74     }
75
76     public MapServer(ILispDAO dao, boolean overwrite, boolean authenticate, boolean iterateAuthenticationMask) {
77         super(dao, authenticate, iterateAuthenticationMask);
78         this.overwrite = overwrite;
79     }
80
81     private static InetAddress getLocalAddress() {
82         try {
83             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
84             while (interfaces.hasMoreElements()) {
85                 NetworkInterface current = interfaces.nextElement();
86                 LOG.debug("Interface " + current.toString());
87                 if (!current.isUp() || current.isLoopback() || current.isVirtual())
88                     continue;
89                 Enumeration<InetAddress> addresses = current.getInetAddresses();
90                 while (addresses.hasMoreElements()) {
91                     InetAddress current_addr = addresses.nextElement();
92                     // Skip loopback and link local addresses
93                     if (current_addr.isLoopbackAddress() || current_addr.isLinkLocalAddress())
94                         continue;
95                     LOG.debug(current_addr.getHostAddress());
96                     return current_addr;
97                 }
98             }
99         } catch (SocketException se) {
100         }
101         return null;
102     }
103
104     private static MapRequest buildSMR(EidToLocatorRecord eidRecord) {
105         MapRequestBuilder builder = new MapRequestBuilder();
106         builder.setAuthoritative(false);
107         builder.setMapDataPresent(false);
108         builder.setPitr(false);
109         builder.setProbe(false);
110         builder.setSmr(true);
111         builder.setSmrInvoked(false);
112
113         builder.setEidRecord(new ArrayList<org.opendaylight.yang.gen.v1.lispflowmapping.rev131031.eidrecords.EidRecord>());
114         LispAddressContainer container = eidRecord.getLispAddressContainer();
115         builder.getEidRecord().add(new EidRecordBuilder().setMask((short) eidRecord.getMaskLength()).setLispAddressContainer(container).build());
116
117         builder.setItrRloc(new ArrayList<ItrRloc>());
118         builder.getItrRloc().add(new ItrRlocBuilder().setLispAddressContainer(LispAFIConvertor.toContainer(getLocalAddress())).build());
119
120         builder.setMapReply(null);
121         builder.setNonce(new Random().nextLong());
122
123         // XXX For now we set source EID to queried EID...
124         builder.setSourceEid(new SourceEidBuilder().setLispAddressContainer(container).build());
125         return builder.build();
126     }
127
128     public void handleMapRegister(MapRegister mapRegister, boolean smr, IMapNotifyHandler callback) {
129         if (dao == null) {
130             LOG.warn("handleMapRegister called while dao is uninitialized");
131         } else {
132             boolean failed = false;
133             String password = null;
134             for (EidToLocatorRecord eidRecord : mapRegister.getEidToLocatorRecord()) {
135                 if (shouldAuthenticate()) {
136                     password = getPassword(eidRecord.getLispAddressContainer(), eidRecord.getMaskLength());
137                     if (!LispAuthenticationUtil.validate(mapRegister, password)) {
138                         LOG.warn("Authentication failed");
139                         failed = true;
140                         break;
141                     }
142                 }
143                 boolean mappingChanged = saveRlocs(eidRecord, smr);
144                 if (smr && mappingChanged) {
145                     HashSet<MappingServiceSubscriberRLOC> subscribers = getSubscribers(eidRecord.getLispAddressContainer(),
146                             eidRecord.getMaskLength());
147                     handleSmr(eidRecord, subscribers, callback);
148                 }
149             }
150             if (!failed) {
151                 MapNotifyBuilder builder = new MapNotifyBuilder();
152                 if (BooleanUtils.isTrue(mapRegister.isWantMapNotify())) {
153                     LOG.trace("MapRegister wants MapNotify");
154                     MapNotifyBuilderHelper.setFromMapRegister(builder, mapRegister);
155                     if (shouldAuthenticate()) {
156                         builder.setAuthenticationData(LispAuthenticationUtil.createAuthenticationData(builder.build(), password));
157                     }
158                     callback.handleMapNotify(builder.build());
159                 }
160             }
161         }
162     }
163
164     public boolean saveRlocs(EidToLocatorRecord eidRecord, boolean checkForChanges) {
165         List<MappingServiceRLOCGroup> oldLocators = null, newLocators = null;
166         IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(eidRecord.getLispAddressContainer(), eidRecord.getMaskLength());
167         Map<String, MappingServiceRLOCGroup> rlocGroups = new HashMap<String, MappingServiceRLOCGroup>();
168         if (eidRecord.getLocatorRecord() != null) {
169             for (LocatorRecord locatorRecord : eidRecord.getLocatorRecord()) {
170                 String subkey = getAddressKey(locatorRecord.getLispAddressContainer().getAddress());
171                 if (!rlocGroups.containsKey(subkey)) {
172                     rlocGroups.put(subkey, new MappingServiceRLOCGroup(eidRecord.getRecordTtl(), eidRecord.getAction(), eidRecord.isAuthoritative()));
173                 }
174                 rlocGroups.get(subkey).addRecord(locatorRecord);
175             }
176         }
177         List<MappingEntry<MappingServiceRLOCGroup>> entries = new ArrayList<>();
178         for (String subkey : rlocGroups.keySet()) {
179             entries.add(new MappingEntry<>(subkey, rlocGroups.get(subkey)));
180         }
181         if (checkForChanges) {
182             oldLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
183         }
184         dao.put(key, entries.toArray(new MappingEntry[entries.size()]));
185         if (checkForChanges) {
186             newLocators = DAOMappingUtil.getLocatorsByEidToLocatorRecord(eidRecord, dao, shouldIterateMask());
187             if (!newLocators.equals(oldLocators)) {
188                 return true;
189             }
190         }
191         return false;
192     }
193
194     private String getAddressKey(Address address) {
195         if (address instanceof LcafKeyValue) {
196             LcafKeyValue keyVal = (LcafKeyValue) address;
197             if (keyVal.getKey().getPrimitiveAddress() instanceof DistinguishedName) {
198                 return ((DistinguishedName) keyVal.getKey().getPrimitiveAddress()).getDistinguishedName();
199             }
200         }
201         if (shouldOverwrite()) {
202             return ADDRESS_SUBKEY;
203         } else {
204             return String.valueOf(address.hashCode());
205         }
206     }
207
208     public String getAuthenticationKey(LispAddressContainer address, int maskLen) {
209         return getPassword(address, maskLen);
210     }
211
212     public void removeAuthenticationKey(LispAddressContainer address, int maskLen) {
213         IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
214         dao.removeSpecific(key, PASSWORD_SUBKEY);
215     }
216
217     public void addAuthenticationKey(LispAddressContainer address, int maskLen, String key) {
218         IMappingServiceKey mappingServiceKey = MappingServiceKeyUtil.generateMappingServiceKey(address, maskLen);
219         dao.put(mappingServiceKey, new MappingEntry<String>(PASSWORD_SUBKEY, key));
220     }
221
222     public void removeMapping(LispAddressContainer address, int maskLen, boolean smr, IMapNotifyHandler callback) {
223         EidRecord eid = new EidRecordBuilder().setLispAddressContainer(address).setMask((short) maskLen).build();
224         Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping = DAOMappingUtil.getMappingForEidRecord(eid, dao);
225         if (smr) {
226             HashSet<MappingServiceSubscriberRLOC> subscribers = getSubscribers(address, maskLen);
227             // mapping is removed before first SMR is sent to avoid inconsistent replies
228             removeMappingRlocs(mapping);
229             handleSmr(new EidToLocatorRecordBuilder().setLispAddressContainer(address).
230                     setMaskLength((short) maskLen).build(), subscribers, callback);
231             dao.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
232         } else {
233             removeMappingRlocs(mapping);
234             dao.removeSpecific(mapping.getKey(), SUBSCRIBERS_SUBKEY);
235         }
236     }
237
238     private void removeMappingRlocs(Entry<IMappingServiceKey, List<MappingServiceRLOCGroup>> mapping) {
239         for (MappingServiceRLOCGroup group : mapping.getValue()) {
240             for (LocatorRecord record : group.getRecords()) {
241                 dao.removeSpecific(mapping.getKey(), getAddressKey(record.getLispAddressContainer().getAddress()));
242             }
243         }
244     }
245
246     private void handleSmr(EidToLocatorRecord record, HashSet<MappingServiceSubscriberRLOC> subscribers,
247             IMapNotifyHandler callback) {
248         if (subscribers == null) {
249             return;
250         }
251         MapRequest mapRequest = buildSMR(record);
252         LOG.trace("Built SMR packet: " + mapRequest.toString());
253         for (MappingServiceSubscriberRLOC rloc : subscribers) {
254             if (rloc.timedOut()) {
255                 LOG.trace("Lazy removing expired subscriber entry " + rloc.toString());
256                 subscribers.remove(rloc);
257             } else {
258                 try {
259                     callback.handleSMR(mapRequest, rloc.getSrcRloc());
260                 } catch (Exception e) {
261                     LOG.error("Errors encountered while handling SMR:" + e.getStackTrace());
262                 }
263             }
264         }
265         IMappingServiceKey key = MappingServiceKeyUtil.generateMappingServiceKey(record.getLispAddressContainer(),
266                 record.getMaskLength());
267         dao.put(key, new MappingEntry<HashSet<MappingServiceSubscriberRLOC>>(SUBSCRIBERS_SUBKEY, subscribers));
268     }
269
270     public boolean shouldOverwrite() {
271         return overwrite;
272     }
273
274     public void setOverwrite(boolean overwrite) {
275         this.overwrite = overwrite;
276     }
277
278 }