Move integration tests to top-level directory
[lispflowmapping.git] / integrationtest / src / test / java / org / opendaylight / lispflowmapping / integrationtest / MappingServiceIntegrationTest.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 package org.opendaylight.lispflowmapping.integrationtest;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.junit.Assert.fail;
14 import static org.ops4j.pax.exam.CoreOptions.composite;
15 import static org.ops4j.pax.exam.CoreOptions.maven;
16 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
17
18 import java.net.DatagramPacket;
19 import java.net.DatagramSocket;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22 import java.net.SocketException;
23 import java.net.SocketTimeoutException;
24 import java.net.UnknownHostException;
25 import java.nio.ByteBuffer;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29
30 import javax.inject.Inject;
31
32 //import org.codehaus.jettison.json.JSONException;
33 //import org.codehaus.jettison.json.JSONObject;
34 //import org.codehaus.jettison.json.JSONTokener;
35 import org.junit.After;
36 import org.junit.Assert;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.junit.runner.RunWith;
40 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
41 import org.opendaylight.lispflowmapping.implementation.LispMappingService;
42 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
43 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
44 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
45 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
46 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
47 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
48 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
49 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
50 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
51 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.OdlLispProtoListener;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.EidBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord.Action;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapregisternotification.MapRegisterBuilder;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRlocBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.SourceEidBuilder;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.RlocBuilder;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.AfiListLcaf;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ApplicationDataLcaf;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ExplicitLocatorPathLcaf;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.InstanceIdType;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.KeyValueAddressLcaf;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.MacAfi;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiList;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationData;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4Prefix;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4PrefixBuilder;
98 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.KeyValueAddress;
99 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Mac;
100 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.afi.list.AfiListBuilder;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.application.data.ApplicationDataBuilder;
103 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.ExplicitLocatorPathBuilder;
104 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop;
105 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop.LrsBits;
106 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.HopBuilder;
107 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.source.dest.key.SourceDestKeyBuilder;
108 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
109 import org.ops4j.pax.exam.Option;
110 import org.ops4j.pax.exam.junit.PaxExam;
111 import org.ops4j.pax.exam.util.Filter;
112 import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
113 import org.ops4j.pax.exam.options.MavenUrlReference;
114 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
115 import org.ops4j.pax.exam.spi.reactors.PerClass;
116 import org.osgi.framework.Bundle;
117 import org.osgi.framework.BundleContext;
118 import org.osgi.framework.InvalidSyntaxException;
119 import org.slf4j.Logger;
120 import org.slf4j.LoggerFactory;
121
122 @RunWith(PaxExam.class)
123 @ExamReactorStrategy(PerClass.class)
124 public class MappingServiceIntegrationTest extends AbstractMdsalTestBase {
125     private static final Logger LOG = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
126
127     private byte[] mapRequestPacket;
128     private byte[] mapRegisterPacketWithNotify;
129     private byte[] mapRegisterPacketWithoutNotify;
130     String lispBindAddress = "127.0.0.1";
131     String ourAddress = "127.0.0.2";
132     private Rloc locatorEid;
133     private DatagramSocket socket;
134     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
135
136     public static final String ODL = "org.opendaylight.controller";
137     public static final String YANG = "org.opendaylight.yangtools";
138     public static final String JERSEY = "com.sun.jersey";
139     private static final int MAX_NOTIFICATION_RETRYS = 20;
140
141     @Override
142     public String getModuleName() {
143         return "mappingservice-impl";
144     }
145
146     @Override
147     public String getInstanceName() {
148         return "mappingservice-default";
149     }
150
151     // This is temporary, since the properties in the pom file are not picked up
152     @Override
153     public String getKarafDistro() {
154         return maven()
155                 .groupId("org.opendaylight.lispflowmapping")
156                 .artifactId("distribution-karaf")
157                 .versionAsInProject()
158                 .type("zip")
159                 .getURL();
160     }
161
162     @Override
163     public MavenUrlReference getFeatureRepo() {
164         return maven()
165                 .groupId("org.opendaylight.lispflowmapping")
166                 .artifactId("features-lispflowmapping")
167                 .classifier("features")
168                 .type("xml")
169                 .versionAsInProject();
170     }
171
172     @Override
173     public String getFeatureName() {
174         return "odl-lispflowmapping-msmr";
175     }
176
177     @Override
178     public Option getLoggingOption() {
179         Option option = editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
180                 logConfiguration(MappingServiceIntegrationTest.class),
181                 LogLevel.DEBUG.name());
182         option = composite(option, super.getLoggingOption());
183         return option;
184     }
185
186     @Test
187     public void testLispFlowMappingFeatureLoad() {
188         Assert.assertTrue(true);
189     }
190
191     @After
192     public void after() {
193         if (socket != null) {
194             socket.close();
195         }
196 //        if (connection != null) {
197 //            connection.disconnect();
198 //        }
199     }
200
201     @Before
202     public void before() throws Exception {
203         areWeReady();
204         locatorEid = LispAddressUtil.asIpv4Rloc("4.3.2.1");
205         socket = initSocket(socket, LispMessage.PORT_NUM);
206
207         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
208         // LISP(Type = 8 - Encapsulated)
209         // IP: 192.168.136.10 -> 153.16.254.1
210         // UDP: 56756
211         // LISP(Type = 1 Map-Request
212         // Record Count: 1
213         // ITR-RLOC count: 0
214         // Source EID AFI: 1
215         // Source EID 1.2.3.4
216         // Nonce: 0x3d8d2acd39c8d608
217         // ITR-RLOC AFI=1 Address=192.168.136.10
218         // Record 1: 153.16.254.1/32
219         mapRequestPacket = extractWSUdpByteArray(new String("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 " //
220                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
221                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
222                 + "0030   00 3c d4 31 00 00 ff 11 56 f3 7f 00 00 02 99 10 "
223                 + "0040   fe 01 dd b4 10 f6 00 28 ef 3a 10 00 00 01 3d 8d "
224                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 " //
225                 + "0060   00 01 99 10 fe 01"));
226
227         // IP: 192.168.136.10 -> 128.223.156.35
228         // UDP: 49289 -> 4342
229         // LISP(Type = 3 Map-Register, P=1, M=1
230         // Record Counter: 1
231         // Nonce: 0
232         // Key ID: 0x0001
233         // AuthDataLength: 20 Data:
234         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
235         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
236         // No-Action
237         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
238         // Priority/Weight: 1/100, Multicast Priority/Weight:
239         // 255/0
240         //
241
242         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
243                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
244                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
245                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
246                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
247                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
248                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
249
250         // IP: 192.168.136.10 -> 128.223.156.35
251         // UDP: 49289 -> 4342
252         // LISP(Type = 3 Map-Register, P=1, M=1
253         // Record Counter: 1
254         // Nonce: 7
255         // Key ID: 0x0000 NO AUTHENTICATION!!
256         // AuthDataLength: 00 Data:
257         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
258         // No-Action
259         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
260         // Priority/Weight: 1/100, Multicast Priority/Weight:
261         // 255/0
262         //
263
264         mapRegisterPacketWithNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
265                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
266                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
267                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
268                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
269                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
270                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
271
272         // IP: 192.168.136.10 -> 128.223.156.35
273         // UDP: 49289 -> 4342
274         // LISP(Type = 3 Map-Register, P=1, M=1
275         // Record Counter: 1
276         // Nonce: 7
277         // Key ID: 0x0000 NO AUTHENTICATION!!
278         // AuthDataLength: 00 Data:
279         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
280         // No-Action
281         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
282         // Priority/Weight: 1/100, Multicast Priority/Weight:
283         // 255/0
284         //
285
286         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(new String("0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
287                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
288                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
289                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
290                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
291                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
292                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
293     }
294
295     @Inject
296     private BundleContext bc;
297     //private HttpURLConnection connection;
298     protected static boolean notificationCalled;
299
300     @Inject @Filter(timeout=60000)
301     private IFlowMapping lms;
302
303     @Inject @Filter(timeout=60000)
304     private IMappingService mapService;
305
306     @Inject @Filter(timeout=10000)
307     private IConfigLispSouthboundPlugin configLispPlugin;
308
309     @Test
310     public void testSimpleUsage() throws Exception {
311         mapRequestSimple();
312         mapRegisterWithMapNotify();
313         mapRegisterWithMapNotifyAndMapRequest();
314         registerAndQuery__MAC();
315         mapRequestMapRegisterAndMapRequest();
316         mapRegisterWithAuthenticationWithoutConfiguringAKey();
317         mapRegisterWithoutMapNotify();
318     }
319
320     @Test
321     public void testLCAFs() throws Exception {
322         //registerAndQuery__SrcDestLCAF();
323         //registerAndQuery__SrcDestLCAFOverlap();
324         //registerAndQuery__KeyValueLCAF();
325         //registerAndQuery__ListLCAF();
326         //registerAndQuery__ApplicationData();
327         //registerAndQuery__TrafficEngineering();
328         //registerAndQuery__SegmentLCAF();
329     }
330
331     @Test
332     public void testMask() throws Exception {
333         //testPasswordExactMatch();                     TODO commented because it needs NB
334         //testPasswordMaskMatch();                      TODO commented because it needs NB
335         eidPrefixLookupIPv4();
336         eidPrefixLookupIPv6();
337     }
338 /*
339     @Test
340     public void testNorthbound() throws Exception {
341         northboundAddKey();
342         northboundAddMapping();
343         northboundDeleteMapping();
344         northboundRetrieveKey();
345         northboundRetrieveMapping();
346         northboundRetrieveSourceDestKey();
347         northboundRetrieveSourceDestMapping();
348     }
349 */
350     @Test
351     public void testOverWriting() throws Exception {
352         //testMapRegisterDosntOverwritesOtherSubKeys(); TODO weird failure, needs debug
353
354         // TODO: remove, we don't support overwrite flag any longer and RLOCs are not saved as independent RLOC groups
355         // testMapRegisterOverwritesSameSubkey();
356         // testMapRegisterOverwritesNoSubkey();
357         // testMapRegisterDoesntOverwritesNoSubkey();
358     }
359
360     @Test
361     public void testTimeOuts() throws Exception {
362         mapRequestMapRegisterAndMapRequestTestTimeout();
363         //mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();   TODO commented because it needs NB
364     }
365
366 //    @Test
367 //    public void testNonProxy() throws Throwable {
368 //        testSimpleNonProxy();
369 //        testNonProxyOtherPort();
370 //        testRecievingNonProxyOnXtrPort();
371 //    }
372
373     @Test
374     public void testSmr() throws Exception {
375         registerQueryRegisterWithSmr();
376     }
377
378     // ------------------------------- Simple Tests ---------------------------
379
380     public void mapRequestSimple() throws SocketTimeoutException {
381         cleanUP();
382
383         // This Map-Request is sent from a source port different from 4342
384         // We close and bind the socket on the correct port
385         if (socket != null) {
386             socket.close();
387         }
388         socket = initSocket(socket, 56756);
389
390         sendPacket(mapRequestPacket);
391         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
392         MapReply reply = MapReplySerializer.getInstance().deserialize(readBuf);
393         assertEquals(4435248268955932168L, reply.getNonce().longValue());
394
395     }
396
397     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
398         cleanUP();
399         sendPacket(mapRegisterPacketWithNotify);
400         MapNotify reply = receiveMapNotify();
401         assertEquals(7, reply.getNonce().longValue());
402     }
403
404     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
405         cleanUP();
406         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
407
408         MapReply mapReply = registerAddressAndQuery(eid);
409
410         assertEquals(4, mapReply.getNonce().longValue());
411         assertEquals(locatorEid, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
412                 .getRloc());
413
414     }
415
416     public void registerAndQuery__MAC() throws SocketTimeoutException {
417         cleanUP();
418         String macAddress = "01:02:03:04:05:06";
419
420         MapReply reply = registerAddressAndQuery(LispAddressUtil.asMacEid(macAddress));
421
422         assertTrue(true);
423         Eid addressFromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
424         assertEquals(MacAfi.class, addressFromNetwork.getAddressType());
425         String macAddressFromReply = ((Mac) addressFromNetwork.getAddress()).getMac().getValue();
426
427         assertEquals(macAddress, macAddressFromReply);
428     }
429
430     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
431         cleanUP();
432         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
433         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
434         mapRequestBuilder.setNonce((long) 4);
435         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
436         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
437         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
438         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
439         mapRequestBuilder.getItrRloc().add(
440                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
441         sendMapRequest(mapRequestBuilder.build());
442         MapReply mapReply = receiveMapReply();
443         assertEquals(4, mapReply.getNonce().longValue());
444         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
445         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
446         mapRegisterbuilder.setWantMapNotify(true);
447         mapRegisterbuilder.setNonce((long) 8);
448         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
449         etlrBuilder.setEid(eid);
450         etlrBuilder.setRecordTtl(254);
451         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
452         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
453         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
454         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
455         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
456         mapRegisterbuilder.getMappingRecordItem().add(
457                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
458         sendMapRegister(mapRegisterbuilder.build());
459         MapNotify mapNotify = receiveMapNotify();
460         assertEquals(8, mapNotify.getNonce().longValue());
461         sleepForSeconds(1);
462         sendMapRequest(mapRequestBuilder.build());
463         mapReply = receiveMapReply();
464         assertEquals(4, mapReply.getNonce().longValue());
465         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
466                 .getLocatorRecord().get(0).getRloc());
467
468     }
469
470     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
471         cleanUP();
472         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
473         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
474         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
475         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
476         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
477         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
478         assertEquals(2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
479         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
480                 .getRloc());
481         assertEquals(rloc1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1)
482                 .getRloc());
483     }
484
485     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
486         cleanUP();
487         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
488         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
489         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
490         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
491         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
492         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
493         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
494         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
495                 .getRloc());
496     }
497
498     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
499         cleanUP();
500         mapService.setMappingOverwrite(true);
501         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
502         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
503         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
504         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
505         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
506         assertEquals(rloc2Value, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
507                 .getRloc());
508     }
509
510     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
511         cleanUP();
512         mapService.setMappingOverwrite(false);
513         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
514         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
515         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
516         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
517         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
518         Rloc rloc1ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc();
519         Rloc rloc2ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1).getRloc();
520         assertTrue((rloc1Value.equals(rloc1ReturnValueContainer) && rloc2Value.equals(rloc2ReturnValueContainer))
521                 || (rloc1Value.equals(rloc2ReturnValueContainer) && rloc2Value.equals(rloc1ReturnValueContainer)));
522     }
523
524     private MapReply sendMapRegisterTwiceWithDiffrentValues(Eid eid, Rloc rloc1, Rloc rloc2)
525             throws SocketTimeoutException {
526         MapRegister mb = createMapRegister(eid, rloc1);
527         MapNotify mapNotify = lms.handleMapRegister(mb);
528         MapRequest mr = createMapRequest(eid);
529         MapReply mapReply = lms.handleMapRequest(mr);
530         assertEquals(mb.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
531                 .getLocatorRecord().get(0).getRloc());
532         mb = createMapRegister(eid, rloc2);
533         mapNotify = lms.handleMapRegister(mb);
534         assertEquals(8, mapNotify.getNonce().longValue());
535         mr = createMapRequest(eid);
536         sendMapRequest(mr);
537         mapReply = lms.handleMapRequest(mr);
538         return mapReply;
539     }
540
541     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
542         cleanUP();
543         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
544         try {
545             receivePacket(3000);
546             // If didn't timeout then fail:
547             fail();
548         } catch (SocketTimeoutException ste) {
549         }
550     }
551
552     public void mapRegisterWithoutMapNotify() {
553         cleanUP();
554         sendPacket(mapRegisterPacketWithoutNotify);
555         try {
556             receivePacket(3000);
557             // If didn't timeout then fail:
558             fail();
559         } catch (SocketTimeoutException ste) {
560         }
561     }
562
563     public void registerQueryRegisterWithSmr() throws SocketTimeoutException {
564         cleanUP();
565         lms.setShouldUseSmr(true);
566
567         sendPacket(mapRegisterPacketWithNotify);
568         receiveMapNotify();
569
570         sleepForSeconds(1);
571         sendPacket(mapRequestPacket);
572         sleepForSeconds(1);
573
574         mapRegisterPacketWithoutNotify[mapRegisterPacketWithoutNotify.length - 1] += 1;
575         sendPacket(mapRegisterPacketWithoutNotify);
576
577         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
578         MapRequest smr = MapRequestSerializer.getInstance().deserialize(readBuf);
579         assertTrue(smr.isSmr());
580         Eid sourceEid = smr.getSourceEid().getEid();
581         assertTrue(LispAddressUtil.asIpv4Eid("153.16.254.1").equals(sourceEid));
582         Eid smrEid = smr.getEidItem().get(0).getEid();
583         assertTrue(LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32").equals(smrEid));
584     }
585
586     // --------------------- Northbound Tests ---------------------------
587 /*
588     private void northboundAddKey() throws Exception {
589         cleanUP();
590         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("1.2.3.4");
591         int mask = 32;
592         String pass = "asdf";
593
594         URL url = createPutURL("key");
595         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
596         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
597
598         String retrievedKey = lms.getAuthenticationKey(LispAddressUtil.toContainer(address), mask);
599
600         // Check stored password matches the one sent
601         assertEquals(pass, retrievedKey);
602
603     }
604
605     private void northboundRetrieveSourceDestKey() throws Exception {
606         cleanUP();
607         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress.primitiveaddress.Ipv4) LispAddressUtil
608                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
609         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress.primitiveaddress.Ipv4) LispAddressUtil
610                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
611         int mask1 = 32;
612         int mask2 = 32;
613         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode())
614                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
615                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build()).setSrcMaskLength((short) mask1)
616                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build()).setDstMaskLength((short) mask2).build();
617         String pass = "asdf";
618
619         lms.addAuthenticationKey(LispAddressUtil.toContainer(sourceDestAddress), mask1, pass);
620
621         // URL url = createGetKeyIPv4URL(address1, mask1);
622         URL url = createGetKeySourceDestURL(address1.getIpv4Address().getAfi(),
623                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getSrcAddress().getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(),
624                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getDstAddress().getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
625         String reply = callURL("GET", null, "application/json", null, url);
626         JSONTokener jt = new JSONTokener(reply);
627         JSONObject json = new JSONObject(jt);
628
629         // test that the password matches what was we expected.
630         assertEquals(pass, json.get("key"));
631
632     }
633
634     private void northboundRetrieveKey() throws Exception {
635         cleanUP();
636         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("10.0.0.1");
637         int mask = 32;
638         String pass = "asdf";
639
640         lms.addAuthenticationKey(LispAddressUtil.toContainer(address), mask, pass);
641
642         URL url = createGetKeyIPv4URL(address, mask);
643         String reply = callURL("GET", null, "application/json", null, url);
644         JSONTokener jt = new JSONTokener(reply);
645         JSONObject json = new JSONObject(jt);
646
647         // test that the password matches what was we expected.
648         assertEquals(pass, json.get("key"));
649
650     }
651
652     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
653         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
654                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
655     }
656
657     private void northboundAddMapping() throws Exception {
658         cleanUP();
659         String pass = "asdf";
660         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
661         int mask = 32;
662         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
663
664         // NB add mapping always checks the key
665         lms.addAuthenticationKey(LispAddressUtil.toContainer(eid), mask, pass);
666
667         URL url = createPutURL("mapping");
668         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
669         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
670
671         // Retrieve the RLOC from the database
672         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
673         mapRequestBuilder.setPitr(false);
674         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
675         mapRequestBuilder.getEidItem().add(
676                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(LispAddressUtil.toContainer(eid)).build());
677         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
678
679         LispIpv4Address retrievedRloc = (LispIpv4Address) LispAddressUtil.toAFI(
680                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getLispAddressContainer());
681
682         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
683
684     }
685
686     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
687         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ " + "\"proxyMapReply\" : false, "
688                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : " + "{ " + "\"ipAddress\" : \""
689                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "}," + "\"mapVersion\" : 0,"
690                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ " + "\"multicastPriority\" : 1,"
691                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\"," + "\"afi\" : "
692                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50," + "\"rlocProbed\" : false, "
693                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], " + "\"recordTtl\" : 100" + "} " + "], "
694                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
695
696         return jsonString;
697     }
698
699     private void northboundRetrieveMapping() throws Exception {
700         cleanUP();
701         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
702         int mask = 32;
703         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
704         // Insert mapping in the database
705         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
706         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
707         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
708         etlr.setMaskLength((short) mask);
709         etlr.setRecordTtl(254);
710         etlr.setAuthoritative(false);
711         etlr.setAction(Action.NoAction);
712         LocatorRecordBuilder record = new LocatorRecordBuilder();
713         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
714         record.setRouted(true);
715         record.setRlocProbed(false);
716         record.setLocalLocator(false);
717         record.setPriority((short) 1);
718         record.setWeight((short) 50);
719         record.setMulticastPriority((short) 1);
720         record.setMulticastWeight((short) 1);
721         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
722         etlr.getLocatorRecord().add(record.build());
723         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
724         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
725         lms.handleMapRegister(mapRegister.build(), false);
726
727         // Get mapping using NB interface. No IID used
728         URL url = createGetMappingIPv4URL(0, eid, mask);
729         String reply = callURL("GET", null, "application/json", null, url);
730         JSONTokener jt = new JSONTokener(reply);
731         JSONObject json = new JSONObject(jt);
732
733         // With just one locator, locators is not a JSONArray
734         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric").getString("ipAddress");
735
736         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
737
738     }
739
740     private void northboundDeleteMapping() throws Exception {
741         cleanUP();
742         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
743         int mask = 32;
744         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
745         // Insert mapping in the database
746         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
747         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
748         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
749         etlr.setMaskLength((short) mask);
750         etlr.setRecordTtl(254);
751         etlr.setAuthoritative(false);
752         etlr.setAction(Action.NoAction);
753         LocatorRecordBuilder record = new LocatorRecordBuilder();
754         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
755         record.setRouted(true);
756         record.setRlocProbed(false);
757         record.setLocalLocator(false);
758         record.setPriority((short) 1);
759         record.setWeight((short) 50);
760         record.setMulticastPriority((short) 1);
761         record.setMulticastWeight((short) 1);
762         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
763         etlr.getLocatorRecord().add(record.build());
764         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
765         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
766         lms.handleMapRegister(mapRegister.build(), false);
767
768         // Delete mapping using NB interface. No IID used
769         URL url = createDeleteMappingIPv4URL(0, eid, mask);
770         String reply = callURL("DELETE", null, "application/json", null, url);
771
772         // Get mapping using NB interface. No IID used
773         url = createGetMappingIPv4URL(0, eid, mask);
774         reply = callURL("GET", null, "application/json", null, url);
775         JSONTokener jt = new JSONTokener(reply);
776         JSONObject json = new JSONObject(jt);
777
778         // With just one locator, locators is not a JSONArray
779         assertEquals(json.getJSONArray("locators").length(), 0);
780     }
781
782     private void northboundRetrieveSourceDestMapping() throws Exception {
783         cleanUP();
784         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress.primitiveaddress.Ipv4) LispAddressUtil
785                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
786         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress.primitiveaddress.Ipv4) LispAddressUtil
787                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
788         int mask1 = 32;
789         int mask2 = 32;
790         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(AddressFamilyNumberEnum.LCAF.getIanaCode())
791                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
792                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build()).setSrcMaskLength((short) mask1)
793                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build()).setDstMaskLength((short) mask2).build();
794         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
795
796         // Insert mapping in the database
797         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
798         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
799         etlr.setLispAddressContainer(LispAddressUtil.toContainer(sourceDestAddress));
800         etlr.setMaskLength((short) mask1);
801         etlr.setRecordTtl(254);
802         etlr.setAuthoritative(false);
803         etlr.setAction(Action.NoAction);
804         LocatorRecordBuilder record = new LocatorRecordBuilder();
805         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
806         record.setRouted(true);
807         record.setRlocProbed(false);
808         record.setLocalLocator(false);
809         record.setPriority((short) 1);
810         record.setWeight((short) 50);
811         record.setMulticastPriority((short) 1);
812         record.setMulticastWeight((short) 1);
813         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
814         etlr.getLocatorRecord().add(record.build());
815         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
816         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
817         lms.handleMapRegister(mapRegister.build(), false);
818
819         // Get mapping using NB interface. No IID used
820         URL url = createGetMappingSourceDestURL(address1.getIpv4Address().getAfi(),
821                 address1.getIpv4Address().getIpv4Address().getValue(),
822                 mask1,
823                 address2.getIpv4Address().getIpv4Address().getValue(),
824                 mask2);
825         String reply = callURL("GET", null, "application/json", null, url);
826         JSONTokener jt = new JSONTokener(reply);
827         JSONObject json = new JSONObject(jt);
828
829         // With just one locator, locators is not a JSONArray
830         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric").getString("ipAddress");
831
832         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
833
834     }
835
836     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
837         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key", address.getAfi().shortValue(),
838                 address.getIpv4Address().getValue(), mask);
839         URL url = new URL(restUrl);
840         return url;
841     }
842
843     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask) throws MalformedURLException {
844         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d", "key", afi, srcAddress, srcMask,
845                 dstAddress, dstMask);
846         URL url = new URL(restUrl);
847         return url;
848     }
849
850     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask) throws MalformedURLException {
851         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d", "mapping", afi, srcAddress,
852                 srcMask, dstAddress, dstMask);
853         URL url = new URL(restUrl);
854         return url;
855     }
856
857     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
858         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping", iid, address.getAfi()
859                 .shortValue(), address.getIpv4Address().getValue(), mask);
860         URL url = new URL(restUrl);
861         return url;
862     }
863
864     private URL createDeleteMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
865         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping", iid, address.getAfi()
866                 .shortValue(), address.getIpv4Address().getValue(), mask);
867         URL url = new URL(restUrl);
868         return url;
869     }
870
871     private URL createPutURL(String resource) throws MalformedURLException {
872
873         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
874
875         URL url = new URL(restUrl);
876         return url;
877     }
878
879     private String createAuthenticationString() {
880         String authString = "admin:admin";
881         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
882         String authStringEnc = new String(authEncBytes);
883         return authStringEnc;
884     }
885
886     private String callURL(String method, String content, String accept, String body, URL url) throws IOException, JSONException {
887         String authStringEnc = createAuthenticationString();
888         connection = (HttpURLConnection) url.openConnection();
889         connection.setRequestMethod(method);
890         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
891         if (content != null) {
892             connection.setRequestProperty("Content-Type", content);
893         }
894         if (accept != null) {
895             connection.setRequestProperty("Accept", accept);
896         }
897         if (body != null) {
898             // now add the request body
899             connection.setDoOutput(true);
900             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
901             wr.write(body);
902             wr.flush();
903         }
904         connection.connect();
905
906         // getting the result, first check response code
907         Integer httpResponseCode = connection.getResponseCode();
908
909         if (httpResponseCode > 299) {
910             LOG.trace("HTTP Address: " + url);
911             LOG.trace("HTTP Response Code: " + httpResponseCode);
912             fail();
913         }
914
915         InputStream is = connection.getInputStream();
916         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
917         StringBuilder sb = new StringBuilder();
918         int cp;
919         while ((cp = rd.read()) != -1) {
920             sb.append((char) cp);
921         }
922         is.close();
923         connection.disconnect();
924         return (sb.toString());
925     }
926
927     // timePeriod - in ms
928     public void assertNoPacketReceived(int timePeriod) {
929         try {
930             receivePacket(timePeriod);
931             // If didn't timeout then fail:
932             fail();
933         } catch (SocketTimeoutException ste) {
934         }
935     }
936 */
937     // ------------------------------- Mask Tests ---------------------------
938
939     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
940         cleanUP();
941         runPrefixTest(LispAddressUtil.asIpv4PrefixEid("1.2.3.4/16"), LispAddressUtil.asIpv4PrefixEid("1.2.3.2/32"),
942                 LispAddressUtil.asIpv4PrefixEid("1.1.1.1/32"));
943     }
944
945     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
946         cleanUP();
947         runPrefixTest(LispAddressUtil.asIpv6PrefixEid("1:2:3:4:5:6:7:8/64"), LispAddressUtil.asIpv6PrefixEid("1:2:3:4:5:1:2:3/128"),
948                 LispAddressUtil.asIpv6PrefixEid("1:2:3:1:2:3:1:2/128"));
949     }
950
951     private void runPrefixTest(Eid registerEID, Eid matchedAddress, Eid unMatchedAddress)
952             throws SocketTimeoutException {
953
954         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
955         mapRegister.setWantMapNotify(true);
956         mapRegister.setNonce((long) 8);
957         mapRegister.setWantMapNotify(true);
958         mapRegister.setKeyId((short) 0);
959         mapRegister.setAuthenticationData(new byte[0]);
960         mapRegister.setNonce((long) 8);
961         mapRegister.setProxyMapReply(false);
962         MappingRecordBuilder etlr = new MappingRecordBuilder();
963         etlr.setRecordTtl(254);
964         etlr.setAction(Action.NoAction);
965         etlr.setAuthoritative(false);
966         etlr.setMapVersion((short) 0);
967         etlr.setEid(registerEID);
968         etlr.setRecordTtl(254);
969         LocatorRecordBuilder record = new LocatorRecordBuilder();
970         record.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
971         record.setLocalLocator(false);
972         record.setRlocProbed(false);
973         record.setRouted(true);
974         record.setMulticastPriority((short) 0);
975         record.setMulticastWeight((short) 0);
976         record.setPriority((short) 0);
977         record.setWeight((short) 0);
978         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
979         etlr.getLocatorRecord().add(record.build());
980         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
981         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
982         sendMapRegister(mapRegister.build());
983         MapNotify mapNotify = receiveMapNotify();
984         assertEquals(8, mapNotify.getNonce().longValue());
985         sleepForSeconds(1);
986         MapRequestBuilder mapRequest = new MapRequestBuilder();
987         mapRequest.setNonce((long) 4);
988         mapRequest.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
989         mapRequest.setEidItem(new ArrayList<EidItem>());
990         mapRequest.setAuthoritative(false);
991         mapRequest.setMapDataPresent(false);
992         mapRequest.setPitr(false);
993         mapRequest.setProbe(false);
994         mapRequest.setSmr(false);
995         mapRequest.setSmrInvoked(false);
996         mapRequest.getEidItem().add(new EidItemBuilder().setEid(matchedAddress).build());
997         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
998         mapRequest.getItrRloc().add(
999                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1000         sendMapRequest(mapRequest.build());
1001         MapReply mapReply = receiveMapReply();
1002         assertEquals(4, mapReply.getNonce().longValue());
1003         assertEquals(record.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1004         mapRequest.setEidItem(new ArrayList<EidItem>());
1005         mapRequest.getEidItem().add(new EidItemBuilder().setEid(unMatchedAddress).build());
1006         sendMapRequest(mapRequest.build());
1007         mapReply = receiveMapReply();
1008         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1009     }
1010 /*
1011     // This registers an IP with a MapRegister, then adds a password via the
1012     // northbound REST API
1013     // and checks that the password works
1014     public void testPasswordExactMatch() throws Exception {
1015         cleanUP();
1016         String ipString = "10.0.0.1";
1017         LispIpv4Address address = LispAddressUtil.asIPAfiAddress(ipString);
1018         int mask = 32;
1019         String pass = "pass";
1020
1021         URL url = createPutURL("key");
1022
1023         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
1024
1025         LOG.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
1026         LOG.trace("Address: " + address);
1027
1028         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232, (byte) 31, (byte) 249, (byte) 87,
1029                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53, (byte) 196, (byte) 62 };
1030
1031         byte[] zeros = new byte[20];
1032
1033         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1034
1035         // build a MapRegister
1036         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1037         mapRegister.setWantMapNotify(true);
1038         mapRegister.setNonce((long) 8);
1039         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1040         etlr.setLispAddressContainer(LispAddressUtil.toContainer(address));
1041         etlr.setMaskLength((short) mask);
1042         etlr.setRecordTtl(254);
1043         LocatorRecordBuilder record = new LocatorRecordBuilder();
1044         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1045         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1046         etlr.getLocatorRecord().add(record.build());
1047         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1048         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1049
1050         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1051         mapRegister.setAuthenticationData(zeros);
1052
1053         sendMapRegister(mapRegister.build());
1054         assertNoPacketReceived(3000);
1055
1056         mapRegister.setAuthenticationData(expectedSha);
1057
1058         sendMapRegister(mapRegister.build());
1059
1060         assertMapNotifyRecieved();
1061     }
1062
1063     public void testPasswordMaskMatch() throws Exception {
1064         cleanUP();
1065         LispIpv4Address addressInRange = LispAddressUtil.asIPAfiAddress("10.20.30.40");
1066         LispIpv4Address addressOutOfRange = LispAddressUtil.asIPAfiAddress("20.40.30.40");
1067         LispIpv4Address range = LispAddressUtil.asIPAfiAddress("10.20.30.0");
1068
1069         int mask = 32;
1070         String pass = "pass";
1071
1072         URL url = createPutURL("key");
1073         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
1074
1075         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1076         // build a MapRegister
1077         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1078
1079         mapRegister.setWantMapNotify(true);
1080         mapRegister.setNonce((long) 8);
1081         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1082         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressInRange));
1083         etlr.setMaskLength((short) mask);
1084         etlr.setRecordTtl(254);
1085         LocatorRecordBuilder record = new LocatorRecordBuilder();
1086         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1087         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1088         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1089         etlr.getLocatorRecord().add(record.build());
1090         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1091         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1092
1093         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1094         mapRegister
1095                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4, -67, -113, 104, -110, -71 });
1096
1097         sendMapRegister(mapRegister.build());
1098
1099         assertMapNotifyRecieved();
1100
1101         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressOutOfRange));
1102         mapRegister
1103                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123, -71, -14, -99, 67, -23, -73 });
1104
1105         sendMapRegister(mapRegister.build());
1106         assertNoPacketReceived(3000);
1107     }
1108 */
1109     // takes an address, packs it in a MapRegister and sends it
1110     private void registerAddress(Eid eid) throws SocketTimeoutException {
1111         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1112         mapRegisterBuilder.setWantMapNotify(true);
1113         mapRegisterBuilder.setKeyId((short) 0);
1114         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1115         mapRegisterBuilder.setNonce((long) 8);
1116         mapRegisterBuilder.setProxyMapReply(false);
1117         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1118         etlrBuilder.setEid(eid);
1119         etlrBuilder.setRecordTtl(254);
1120         etlrBuilder.setAction(Action.NoAction);
1121         etlrBuilder.setAuthoritative(false);
1122         etlrBuilder.setMapVersion((short) 0);
1123         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1124         recordBuilder.setLocalLocator(false);
1125         recordBuilder.setRlocProbed(false);
1126         recordBuilder.setRouted(true);
1127         recordBuilder.setMulticastPriority((short) 0);
1128         recordBuilder.setMulticastWeight((short) 0);
1129         recordBuilder.setPriority((short) 0);
1130         recordBuilder.setWeight((short) 0);
1131         recordBuilder.setRloc(locatorEid);
1132         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1133         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1134         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1135         mapRegisterBuilder.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1136         sendMapRegister(mapRegisterBuilder.build());
1137         MapNotify mapNotify = receiveMapNotify();
1138         assertEquals(8, mapNotify.getNonce().longValue());
1139     }
1140
1141     private MapReply queryForAddress(Eid eid, String srcEid) throws SocketTimeoutException {
1142         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1143         mapRequestBuilder.setNonce((long) 4);
1144         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1145         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1146         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1147         if (srcEid != null) {
1148             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(srcEid)).build());
1149         } else {
1150             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1151         }
1152         mapRequestBuilder.getItrRloc().add(
1153                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1154         mapRequestBuilder.setAuthoritative(false);
1155         mapRequestBuilder.setMapDataPresent(false);
1156         mapRequestBuilder.setPitr(false);
1157         mapRequestBuilder.setProbe(false);
1158         mapRequestBuilder.setSmr(false);
1159         mapRequestBuilder.setSmrInvoked(false);
1160         sendMapRequest(mapRequestBuilder.build());
1161         return receiveMapReply();
1162     }
1163
1164     // takes an address, packs it in a MapRegister, sends it, returns the
1165     // MapReply
1166     private MapReply registerAddressAndQuery(Eid eid) throws SocketTimeoutException {
1167         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1168         mapRegisterBuilder.setWantMapNotify(true);
1169         mapRegisterBuilder.setKeyId((short) 0);
1170         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1171         mapRegisterBuilder.setNonce((long) 8);
1172         mapRegisterBuilder.setProxyMapReply(false);
1173         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1174         etlrBuilder.setEid(eid);
1175         etlrBuilder.setRecordTtl(254);
1176         etlrBuilder.setAction(Action.NoAction);
1177         etlrBuilder.setAuthoritative(false);
1178         etlrBuilder.setMapVersion((short) 0);
1179         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1180         recordBuilder.setLocalLocator(false);
1181         recordBuilder.setRlocProbed(false);
1182         recordBuilder.setRouted(true);
1183         recordBuilder.setMulticastPriority((short) 0);
1184         recordBuilder.setMulticastWeight((short) 0);
1185         recordBuilder.setPriority((short) 0);
1186         recordBuilder.setWeight((short) 0);
1187         recordBuilder.setRloc(locatorEid);
1188         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1189         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1190         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1191         mapRegisterBuilder.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1192         sendMapRegister(mapRegisterBuilder.build());
1193         MapNotify mapNotify = receiveMapNotify();
1194         assertEquals(8, mapNotify.getNonce().longValue());
1195         // wait for the notifications to propagate
1196         sleepForSeconds(1);
1197         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1198         mapRequestBuilder.setNonce((long) 4);
1199         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1200         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1201         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1202         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1203         mapRequestBuilder.getItrRloc().add(
1204                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1205         mapRequestBuilder.setAuthoritative(false);
1206         mapRequestBuilder.setMapDataPresent(false);
1207         mapRequestBuilder.setPitr(false);
1208         mapRequestBuilder.setProbe(false);
1209         mapRequestBuilder.setSmr(false);
1210         mapRequestBuilder.setSmrInvoked(false);
1211         sendMapRequest(mapRequestBuilder.build());
1212         return receiveMapReply();
1213     }
1214
1215     // ------------------------------- LCAF Tests ---------------------------
1216
1217     @Test
1218     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
1219         cleanUP();
1220         String ipPrefix = "10.20.30.200/32";
1221         String macString = "01:02:03:04:05:06";
1222
1223         SourceDestKeyBuilder builder = new SourceDestKeyBuilder();
1224         builder.setSource(new SimpleAddress(new IpPrefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix(ipPrefix))));
1225         builder.setDest(new SimpleAddress(new MacAddress(macString)));
1226
1227         EidBuilder eb = new EidBuilder();
1228         eb.setAddressType(SourceDestKeyLcaf.class);
1229         eb.setVirtualNetworkId(null);
1230         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKeyBuilder()
1231                 .setSourceDestKey(builder.build()).build());
1232
1233         MapReply reply = registerAddressAndQuery(eb.build());
1234
1235         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1236         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1237         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1238
1239         SimpleAddress receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource();
1240         SimpleAddress receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest();
1241
1242         assertNotNull(receivedAddr1.getIpPrefix().getIpv4Prefix());
1243         assertNotNull(receivedAddr2.getMacAddress());
1244
1245         IpPrefix receivedIP = receivedAddr1.getIpPrefix();
1246         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1247
1248         assertEquals(ipPrefix, receivedIP.getIpv4Prefix().getValue());
1249         assertEquals(macString, receivedMAC.getValue());
1250     }
1251
1252     @Test
1253     public void registerAndQuery__SrcDestLCAFOverlap() throws SocketTimeoutException {
1254         cleanUP();
1255         String ipString1 = "10.10.10.0";
1256         String ipString2 = "20.20.20.0";
1257         String ipPrefix1 = ipString1 + "/24";
1258         String ipPrefix2 = ipString2 + "/24";
1259
1260         Eid srcDst = LispAddressUtil.asSrcDstEid(ipString1, ipString2, 24, 24, 0);
1261         registerAddress(LispAddressUtil.asIpv4PrefixEid(ipPrefix2));
1262         registerAddress(srcDst);
1263
1264         // exact match
1265         MapReply reply = queryForAddress(srcDst, null);
1266
1267         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1268         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1269         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1270
1271         IpPrefix receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource().getIpPrefix();
1272         IpPrefix receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest().getIpPrefix();
1273
1274         assertNotNull(receivedAddr1.getIpv4Prefix());
1275         assertNotNull(receivedAddr2.getIpv4Prefix());
1276
1277         assertEquals(ipPrefix1, receivedAddr1.getIpv4Prefix().getValue());
1278         assertEquals(ipPrefix2, receivedAddr2.getIpv4Prefix().getValue());
1279
1280         // srcEid/dstEid match
1281         reply = queryForAddress(LispAddressUtil.asIpv4PrefixEid("20.20.20.1/32"), "10.10.10.1");
1282         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1283         assertEquals(Ipv4PrefixAfi.class, fromNetwork.getAddressType());
1284
1285         Ipv4Prefix ipAddr2 = (Ipv4Prefix) fromNetwork.getAddress();
1286         assertEquals(ipPrefix2, ipAddr2.getIpv4Prefix().getValue());
1287
1288         // dstEid match only
1289         reply = queryForAddress(LispAddressUtil.asIpv4PrefixEid("20.20.20.1/32"), "1.2.3.4");
1290         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1291         assertEquals(Ipv4PrefixAfi.class, fromNetwork.getAddressType());
1292
1293         ipAddr2 = (Ipv4Prefix) fromNetwork.getAddress();
1294         assertEquals(ipPrefix2, ipAddr2.getIpv4Prefix().getValue());
1295     }
1296
1297     @Test
1298     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
1299         cleanUP();
1300         String ipString = "10.20.30.200";
1301         String macString = "01:02:03:04:05:06";
1302         SimpleAddress addrToSend1 = new SimpleAddress(new IpAddress(new Ipv4Address(ipString)));
1303         SimpleAddress addrToSend2 = new SimpleAddress(new MacAddress(macString));
1304         Eid kv = LispAddressUtil.asKeyValueAddressEid(addrToSend1, addrToSend2);
1305
1306         MapReply reply = registerAddressAndQuery(kv);
1307
1308         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1309         assertEquals(KeyValueAddressLcaf.class, fromNetwork.getAddressType());
1310         KeyValueAddress keyValueFromNetwork = (KeyValueAddress) fromNetwork.getAddress();
1311
1312         SimpleAddress receivedAddr1 = keyValueFromNetwork.getKeyValueAddress().getKey();
1313         SimpleAddress receivedAddr2 = keyValueFromNetwork.getKeyValueAddress().getValue();
1314
1315         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1316         assertNotNull(receivedAddr2.getMacAddress());
1317
1318         Ipv4Address receivedIP = receivedAddr1.getIpAddress().getIpv4Address();
1319         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1320
1321         assertEquals(ipString, receivedIP.getValue());
1322         assertEquals(macString, receivedMAC.getValue());
1323     }
1324
1325     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
1326         cleanUP();
1327         String macString = "01:02:03:04:05:06";
1328         String ipString = "10.20.255.30";
1329         List<SimpleAddress> addresses = new ArrayList<SimpleAddress>();
1330         addresses.add(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1331         addresses.add(new SimpleAddress(new MacAddress(macString)));
1332         AfiListBuilder listbuilder = new AfiListBuilder();
1333         listbuilder.setAddressList(addresses);
1334
1335         EidBuilder eb = new EidBuilder();
1336         eb.setAddressType(AfiListLcaf.class);
1337         eb.setVirtualNetworkId(null);
1338         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiListBuilder()
1339                 .setAfiList(listbuilder.build()).build());
1340
1341         MapReply reply = registerAddressAndQuery(eb.build());
1342
1343         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1344
1345         assertEquals(AfiListLcaf.class, receivedAddress.getAddressType());
1346
1347         AfiList listAddrFromNetwork = (AfiList) receivedAddress.getAddress();
1348         SimpleAddress receivedAddr1 = listAddrFromNetwork.getAfiList().getAddressList().get(0);
1349         SimpleAddress receivedAddr2 = listAddrFromNetwork.getAfiList().getAddressList().get(1);
1350
1351         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1352         assertNotNull(receivedAddr2.getMacAddress());
1353
1354         assertEquals(macString, receivedAddr2.getMacAddress().getValue());
1355         assertEquals(ipString, receivedAddr1.getIpAddress().getIpv4Address().getValue());
1356     }
1357
1358     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
1359         cleanUP();
1360         String ipString = "10.20.255.30";
1361         int instanceId = 6;
1362
1363         EidBuilder eb = new EidBuilder();
1364         eb.setAddressType(Ipv4PrefixAfi.class);
1365         eb.setVirtualNetworkId(new InstanceIdType((long) instanceId));
1366         eb.setAddress(new Ipv4PrefixBuilder().setIpv4Prefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix(
1367                 ipString)).build());
1368
1369         MapReply reply = registerAddressAndQuery(eb.build());
1370
1371         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1372         assertEquals(Ipv4PrefixAfi.class, receivedAddress.getAddressType());
1373
1374         assertEquals(ipString, ((Ipv4Prefix) receivedAddress.getAddress()).getIpv4Prefix().getValue());
1375
1376         assertEquals(instanceId, receivedAddress.getVirtualNetworkId().getValue().intValue());
1377     }
1378
1379     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
1380         cleanUP();
1381         String macString = "01:02:03:04:05:06";
1382         String ipString = "10.20.255.30";
1383         HopBuilder hopBuilder = new HopBuilder();
1384         hopBuilder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1385         hopBuilder.setLrsBits(new LrsBits(true, false, true));
1386         Hop hop1 = hopBuilder.build();
1387         hopBuilder.setAddress(new SimpleAddress(new MacAddress(macString)));
1388         hopBuilder.setLrsBits(new LrsBits(false, true, false));
1389         Hop hop2 = hopBuilder.build();
1390         ExplicitLocatorPathBuilder elpBuilder = new ExplicitLocatorPathBuilder();
1391         elpBuilder.setHop(new ArrayList<Hop>());
1392         elpBuilder.getHop().add(hop1);
1393         elpBuilder.getHop().add(hop2);
1394
1395         EidBuilder eb = new EidBuilder();
1396         eb.setAddressType(ExplicitLocatorPathLcaf.class);
1397         eb.setVirtualNetworkId(null);
1398         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPathBuilder()
1399                 .setExplicitLocatorPath(elpBuilder.build()).build());
1400
1401         MapReply reply = registerAddressAndQuery(eb.build());
1402
1403         assertEquals(ExplicitLocatorPathLcaf.class, reply.getMappingRecordItem().get(0).getMappingRecord().getEid().getAddressType());
1404
1405         ExplicitLocatorPath receivedAddress = (ExplicitLocatorPath) reply.getMappingRecordItem().get(0).getMappingRecord().getEid().getAddress();
1406
1407         Hop receivedHop1 = receivedAddress.getExplicitLocatorPath().getHop().get(0);
1408         Hop receivedHop2 = receivedAddress.getExplicitLocatorPath().getHop().get(1);
1409
1410         assertEquals(true, receivedHop1.getLrsBits().isLookup());
1411         assertEquals(false, receivedHop1.getLrsBits().isRlocProbe());
1412         assertEquals(true, receivedHop1.getLrsBits().isStrict());
1413
1414         assertEquals(false, receivedHop2.getLrsBits().isLookup());
1415         assertEquals(true, receivedHop2.getLrsBits().isRlocProbe());
1416         assertEquals(false, receivedHop2.getLrsBits().isStrict());
1417
1418         assertNotNull(receivedHop1.getAddress().getIpAddress().getIpv4Address());
1419         assertNotNull(receivedHop2.getAddress().getMacAddress());
1420
1421         assertEquals(ipString, receivedHop1.getAddress().getIpAddress().getIpv4Address().getValue());
1422         assertEquals(macString, receivedHop2.getAddress().getMacAddress().getValue());
1423     }
1424
1425     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
1426         cleanUP();
1427         String ipString = "1.2.3.4";
1428         short protocol = 1;
1429         int ipTOs = 2;
1430         int localPortLow = 3;
1431         int localPortHigh = 4;
1432         int remotePortLow = 4;
1433         int remotePortHigh = 5;
1434
1435         ApplicationDataBuilder builder = new ApplicationDataBuilder();
1436         builder.setIpTos(ipTOs);
1437         builder.setProtocol(protocol);
1438         builder.setLocalPortLow(new PortNumber(localPortLow));
1439         builder.setLocalPortHigh(new PortNumber(localPortHigh));
1440         builder.setRemotePortLow(new PortNumber(remotePortLow));
1441         builder.setRemotePortHigh(new PortNumber(remotePortHigh));
1442         builder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1443
1444         EidBuilder eb = new EidBuilder();
1445         eb.setAddressType(ApplicationDataLcaf.class);
1446         eb.setVirtualNetworkId(null);
1447         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationDataBuilder()
1448                 .setApplicationData(builder.build()).build());
1449         Eid addressToSend = eb.build();
1450
1451         MapReply reply = registerAddressAndQuery(addressToSend);
1452
1453         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1454
1455         assertEquals(ApplicationDataLcaf.class, receivedAddress.getAddressType());
1456
1457         ApplicationData receivedApplicationDataAddress = (ApplicationData) receivedAddress.getAddress();
1458         assertEquals(protocol, receivedApplicationDataAddress.getApplicationData().getProtocol().intValue());
1459         assertEquals(ipTOs, receivedApplicationDataAddress.getApplicationData().getIpTos().intValue());
1460         assertEquals(localPortLow, receivedApplicationDataAddress.getApplicationData().getLocalPortLow().getValue().intValue());
1461         assertEquals(localPortHigh, receivedApplicationDataAddress.getApplicationData().getLocalPortHigh().getValue().intValue());
1462         assertEquals(remotePortLow, receivedApplicationDataAddress.getApplicationData().getRemotePortLow().getValue().intValue());
1463         assertEquals(remotePortHigh, receivedApplicationDataAddress.getApplicationData().getRemotePortHigh().getValue().intValue());
1464
1465         SimpleAddress ipAddressReceived = receivedApplicationDataAddress.getApplicationData().getAddress();
1466         assertEquals(ipString, ipAddressReceived.getIpAddress().getIpv4Address().getValue());
1467     }
1468
1469     // ------------------- TimeOut Tests -----------
1470
1471     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
1472         cleanUP();
1473         Eid eid = LispAddressUtil.asIpv4PrefixEid("1.2.3.4/32");
1474         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1475         mapRequestBuilder.setNonce((long) 4);
1476         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
1477         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1478         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1479         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1480         mapRequestBuilder.getItrRloc().add(
1481                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1482
1483         sendMapRequest(mapRequestBuilder.build());
1484         MapReply mapReply = receiveMapReply();
1485         assertEquals(4, mapReply.getNonce().longValue());
1486         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1487
1488         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
1489         mapRegisterbuilder.setWantMapNotify(true);
1490         mapRegisterbuilder.setNonce((long) 8);
1491
1492         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1493         etlrBuilder.setEid(eid);
1494         etlrBuilder.setMaskLength((short) 32);
1495         etlrBuilder.setRecordTtl(254);
1496
1497         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1498         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1499         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1500         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1501         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1502         mapRegisterbuilder.getMappingRecordItem().add(
1503                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1504
1505         sendMapRegister(mapRegisterbuilder.build());
1506         MapNotify mapNotify = receiveMapNotify();
1507         assertEquals(8, mapNotify.getNonce().longValue());
1508         sleepForSeconds(1);
1509
1510         sendMapRequest(mapRequestBuilder.build());
1511         mapReply = receiveMapReply();
1512         assertEquals(4, mapReply.getNonce().longValue());
1513         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
1514                 .getLocatorRecord().get(0).getRloc());
1515
1516         causeEntryToBeCleaned();
1517         sendMapRequest(mapRequestBuilder.build());
1518         mapReply = receiveMapReply();
1519         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1520     }
1521
1522     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
1523         cleanUP();
1524         Eid eid = LispAddressUtil.asIpv6PrefixEid("1.2.3.4/32");
1525         MapRequest mapRequest = createMapRequest(eid);
1526
1527         testTTLBeforeRegister(mapRequest);
1528
1529         registerForTTL(eid);
1530
1531         testTTLAfterRegister(mapRequest);
1532
1533         causeEntryToBeCleaned();
1534         testTTLAfterClean(mapRequest);
1535
1536         //northboundAddKey();
1537         //testTTLAfterAutherize(mapRequest);
1538
1539     }
1540
1541     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
1542         MapReply mapReply;
1543         sendMapRequest(mapRequest);
1544         mapReply = receiveMapReply();
1545         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
1546     }
1547
1548     private void causeEntryToBeCleaned() {
1549         // TODO XXX for the time being, to keep master and stable/lithium in sync, we need to remove the forceful
1550         // expiration of DAO entries. Once we're past this, we'll have to expose methods to setTimeUnit(TimeUnit)
1551         // and cleanOld() (expired) entries in IFlowMapping (and perhaps ILispDAO) and use them here.
1552         mapService.cleanCachedMappings();
1553     }
1554
1555     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
1556         MapReply mapReply;
1557         sendMapRequest(mapRequest);
1558         mapReply = receiveMapReply();
1559         assertEquals(LispAddressUtil.asIpv4Rloc("4.3.2.1"), mapReply.getMappingRecordItem().get(0).getMappingRecord()
1560                 .getLocatorRecord().get(0).getRloc());
1561         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
1562     }
1563
1564     private void registerForTTL(Eid eid) throws SocketTimeoutException {
1565         MapRegister mapRegister = createMapRegister(eid);
1566         sendMapRegister(mapRegister);
1567         assertMapNotifyRecieved();
1568     }
1569
1570     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
1571         MapReply mapReply;
1572         sendMapRequest(mapRequest);
1573         mapReply = receiveMapReply();
1574         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
1575     }
1576 /*
1577     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
1578         MapReply mapReply;
1579         sendMapRequest(mapRequest);
1580         mapReply = receiveMapReply();
1581         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
1582     }
1583 */
1584     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
1585         assertEquals(expectedTTL, mapReply.getMappingRecordItem().get(0).getMappingRecord().getRecordTtl().intValue());
1586         assertEquals(expectedAction, mapReply.getMappingRecordItem().get(0).getMappingRecord().getAction());
1587     }
1588
1589     private MapRegister createMapRegister(Eid eid, Rloc rloc) {
1590         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
1591         mapRegisterbuilder.setWantMapNotify(true);
1592         mapRegisterbuilder.setNonce((long) 8);
1593         mapRegisterbuilder.setKeyId((short) 0);
1594         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1595         etlrBuilder.setEid(eid);
1596         etlrBuilder.setMaskLength((short) 24);
1597         etlrBuilder.setRecordTtl(254);
1598         etlrBuilder.setAuthoritative(false);
1599         etlrBuilder.setAction(Action.NoAction);
1600         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1601         recordBuilder.setRloc(rloc);
1602         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1603         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1604         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1605         mapRegisterbuilder.getMappingRecordItem().add(
1606                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1607         MapRegister mapRegister = mapRegisterbuilder.build();
1608         return mapRegister;
1609     }
1610
1611     private MapRegister createMapRegister(Eid eid) {
1612         return createMapRegister(eid, LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1613     }
1614
1615     private MapRequest createMapRequest(Eid eid) {
1616         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1617         mapRequestBuilder.setNonce((long) 4);
1618         mapRequestBuilder.setPitr(false);
1619         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
1620         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1621         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1622         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1623         mapRequestBuilder.getItrRloc().add(
1624                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1625         MapRequest mr = mapRequestBuilder.build();
1626         return mr;
1627     }
1628
1629     public void testSimpleNonProxy() throws SocketTimeoutException, SocketException {
1630         cleanUP();
1631         String rloc = "127.0.0.3";
1632         int port = LispMessage.PORT_NUM;
1633         Rloc ipRloc = LispAddressUtil.asIpv4Rloc(rloc);
1634         sendProxyMapRequest(rloc, port, ipRloc);
1635
1636     }
1637
1638     public void testNonProxyOtherPort() throws SocketTimeoutException, SocketException {
1639         cleanUP();
1640         String rloc = "127.0.0.3";
1641         int port = 4350;
1642
1643         RlocBuilder rb = new RlocBuilder();
1644         rb.setAddressType(ApplicationDataLcaf.class);
1645         rb.setVirtualNetworkId(null);
1646         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationDataBuilder()
1647                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
1648                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
1649         Rloc adLcaf = rb.build();
1650
1651         LOG.info("testNonProxyOtherPort:" + LispAddressStringifier.getString(adLcaf));
1652         sendProxyMapRequest(rloc, port, adLcaf);
1653
1654     }
1655
1656     private class XtrRequestMappingListener implements OdlLispProtoListener {
1657
1658         @Override
1659         public void onGotMapReply(GotMapReply notification) {
1660         }
1661
1662         @Override
1663         public void onAddMapping(AddMapping notification) {
1664         }
1665
1666         @Override
1667         public void onXtrReplyMapping(XtrReplyMapping notification) {
1668         }
1669
1670         @Override
1671         public void onRequestMapping(RequestMapping notification) {
1672         }
1673
1674         @Override
1675         public void onGotMapNotify(GotMapNotify notification) {
1676         }
1677
1678         @Override
1679         public void onXtrRequestMapping(XtrRequestMapping notification) {
1680         }
1681
1682     }
1683
1684     public void testRecievingNonProxyOnXtrPort() throws SocketTimeoutException, SocketException, Throwable {
1685         cleanUP();
1686         configLispPlugin.shouldListenOnXtrPort(true);
1687         notificationCalled = false;
1688         final String eid = "10.10.10.10/32";
1689         String rloc = "127.0.0.3";
1690         int port = LispMessage.XTR_PORT_NUM;
1691
1692         RlocBuilder rb = new RlocBuilder();
1693         rb.setAddressType(ApplicationDataLcaf.class);
1694         rb.setVirtualNetworkId(null);
1695         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationDataBuilder()
1696                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
1697                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
1698         Rloc adLcaf = rb.build();
1699
1700         final MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
1701         ((LispMappingService) lms).getNotificationService().registerNotificationListener(new XtrRequestMappingListener() {
1702
1703             @Override
1704             public void onXtrRequestMapping(XtrRequestMapping notification) {
1705                 assertEquals(((Ipv4Prefix) mapRequest.getEidItem().get(0).getEid().getAddress())
1706                         .getIpv4Prefix().getValue(), eid);
1707                 notificationCalled = true;
1708                 LOG.warn("notification arrived");
1709             }
1710         });
1711         sendMapRequest(mapRequest, port);
1712         for (int i = 0; i < MAX_NOTIFICATION_RETRYS; i++) {
1713             if (notificationCalled) {
1714                 return;
1715             } else {
1716                 LOG.warn("notification hasn't arrived, sleeping...");
1717                 Thread.sleep(500);
1718             }
1719         }
1720
1721         fail("Notification hasn't arrived");
1722
1723     }
1724
1725     private void sendProxyMapRequest(String rloc, int port, Rloc adLcaf) throws SocketTimeoutException, SocketException {
1726         String eid = "10.1.0.1/32";
1727         MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
1728         sendMapRequest(mapRequest);
1729         DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
1730         MapRequest recievedMapRequest = receiveMapRequest(nonProxySocket);
1731         assertEquals(mapRequest.getNonce(), recievedMapRequest.getNonce());
1732         assertEquals(mapRequest.getSourceEid(), recievedMapRequest.getSourceEid());
1733         assertEquals(mapRequest.getItrRloc(), recievedMapRequest.getItrRloc());
1734         assertEquals(mapRequest.getEidItem(), recievedMapRequest.getEidItem());
1735         nonProxySocket.close();
1736     }
1737
1738     private MapRequest createNonProxyMapRequest(String eid, Rloc adLcaf) throws SocketTimeoutException {
1739         MapRegister mr = createMapRegister(LispAddressUtil.asIpv4PrefixEid(eid));
1740         LocatorRecord record = new LocatorRecordBuilder(mr.getMappingRecordItem().get(0).getMappingRecord()
1741                 .getLocatorRecord().get(0)).setRloc(adLcaf).build();
1742         mr.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().set(0, record);
1743         sendMapRegister(mr);
1744         assertMapNotifyRecieved();
1745         MapRequest mapRequest = createMapRequest(LispAddressUtil.asIpv4PrefixEid(eid));
1746         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
1747         builder.setPitr(true);
1748         mapRequest = builder.build();
1749         return mapRequest;
1750     }
1751
1752     private void assertMapNotifyRecieved() throws SocketTimeoutException {
1753         receiveMapNotify();
1754     }
1755
1756     private MapReply receiveMapReply() throws SocketTimeoutException {
1757         return MapReplySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
1758     }
1759
1760     private MapRequest receiveMapRequest(DatagramSocket datagramSocket) throws SocketTimeoutException {
1761         return MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket(datagramSocket, 30000).getData()));
1762     }
1763
1764     private MapNotify receiveMapNotify() throws SocketTimeoutException {
1765         return MapNotifySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
1766     }
1767
1768     private void sendMapRequest(MapRequest mapRequest) {
1769         sendMapRequest(mapRequest, LispMessage.PORT_NUM);
1770     }
1771
1772     private void sendMapRequest(MapRequest mapRequest, int port) {
1773         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array(), port);
1774     }
1775
1776     private void sendMapRegister(MapRegister mapRegister) {
1777         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
1778     }
1779
1780     private void sendPacket(byte[] bytesToSend) {
1781         sendPacket(bytesToSend, LispMessage.PORT_NUM);
1782     }
1783
1784     private void sendPacket(byte[] bytesToSend, int port) {
1785         try {
1786             DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
1787             initPacketAddress(packet, port);
1788             LOG.trace("Sending packet to LispPlugin on socket, port {}", port);
1789             socket.send(packet);
1790         } catch (Throwable t) {
1791             fail();
1792         }
1793     }
1794
1795     private DatagramPacket receivePacket() throws SocketTimeoutException {
1796         return receivePacket(6000);
1797     }
1798
1799     private DatagramPacket receivePacket(int timeout) throws SocketTimeoutException {
1800         return receivePacket(socket, timeout);
1801     }
1802
1803     private DatagramPacket receivePacket(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
1804         try {
1805             byte[] buffer = new byte[4096];
1806             DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
1807             LOG.trace("Waiting for packet from socket...");
1808             receivedSocket.setSoTimeout(timeout);
1809             receivedSocket.receive(receivePacket);
1810             LOG.trace("Recieved packet from socket!");
1811             return receivePacket;
1812         } catch (SocketTimeoutException ste) {
1813             throw ste;
1814         } catch (Throwable t) {
1815             fail();
1816             return null;
1817         }
1818     }
1819
1820
1821     private void sleepForSeconds(int seconds) {
1822         try {
1823             Thread.sleep(seconds*1000);
1824         } catch (InterruptedException e) {
1825             LOG.warn("Interrupted while sleeping");
1826             e.printStackTrace();
1827         }
1828     }
1829
1830     private void initPacketAddress(DatagramPacket packet, int port) throws UnknownHostException {
1831         packet.setAddress(InetAddress.getByName(lispBindAddress));
1832         packet.setPort(port);
1833     }
1834
1835     private DatagramSocket initSocket(DatagramSocket socket, int port) {
1836         try {
1837             socket = new DatagramSocket(new InetSocketAddress(ourAddress, port));
1838         } catch (SocketException e) {
1839             e.printStackTrace();
1840             fail();
1841         }
1842         return socket;
1843     }
1844
1845     private byte[] extractWSUdpByteArray(String wiresharkHex) {
1846         final int HEADER_LEN = 42;
1847         byte[] res = new byte[1000];
1848         String[] split = wiresharkHex.split(" ");
1849         int counter = 0;
1850         for (String cur : split) {
1851             cur = cur.trim();
1852             if (cur.length() == 2) {
1853                 ++counter;
1854                 if (counter > HEADER_LEN) {
1855                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
1856                 }
1857
1858             }
1859         }
1860         return Arrays.copyOf(res, counter - HEADER_LEN);
1861     }
1862
1863     private String stateToString(int state) {
1864         switch (state) {
1865         case Bundle.ACTIVE:
1866             return "ACTIVE";
1867         case Bundle.INSTALLED:
1868             return "INSTALLED";
1869         case Bundle.RESOLVED:
1870             return "RESOLVED";
1871         case Bundle.UNINSTALLED:
1872             return "UNINSTALLED";
1873         default:
1874             return "Not CONVERTED";
1875         }
1876     }
1877
1878     private void areWeReady() throws InvalidSyntaxException {
1879         try {
1880             Thread.sleep(5000);
1881         } catch (InterruptedException e) {
1882         }
1883
1884         assertNotNull(bc);
1885         boolean debugit = false;
1886         Bundle b[] = bc.getBundles();
1887         for (Bundle element : b) {
1888             int state = element.getState();
1889             LOG.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v" + element.getVersion() + ", state:"
1890                     + stateToString(state));
1891             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
1892                 LOG.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
1893
1894                 // try {
1895                 // String host = element.getHeaders().get("FRAGMENT-HOST");
1896                 // if (host != null) {
1897                 // LOG.warn("Bundle " + element.getSymbolicName() +
1898                 // " is a fragment which is part of: " + host);
1899                 // LOG.warn("Required imports are: " +
1900                 // element.getHeaders().get("IMPORT-PACKAGE"));
1901                 // } else {
1902                 // element.start();
1903                 // }
1904                 // } catch (BundleException e) {
1905                 // LOG.error("BundleException:", e);
1906                 // fail();
1907                 // }
1908
1909                 debugit = true;
1910
1911             }
1912         }
1913         if (debugit) {
1914             LOG.warn(("Do some debugging because some bundle is unresolved"));
1915         }
1916         // assertNotNull(broker);
1917
1918         configLispPlugin.setLispAddress(lispBindAddress);
1919
1920         // Uncomment this code to Know which services were actually loaded to
1921         // BundleContext
1922
1923         /*
1924         for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
1925             LOG.info(sr.getBundle().getSymbolicName());
1926             LOG.info(sr.toString());
1927         }
1928         */
1929
1930         try {
1931             Thread.sleep(1000);
1932         } catch (InterruptedException e) {
1933         }
1934     }
1935
1936     private void cleanUP() {
1937         after();
1938         mapService.cleanCachedMappings();
1939         configLispPlugin.shouldListenOnXtrPort(false);
1940         socket = initSocket(socket, LispMessage.PORT_NUM);
1941
1942     }
1943
1944 }