Fix radix trie last byte prefix comparison
[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.assertNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A;
16 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A_SB;
17 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B;
18 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B_SB;
19 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C;
20 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_RLOC_10;
21 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_SB;
22 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_100_1_SB;
23 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_50_2_SB;
24 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D4;
25 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D5;
26 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_DELETE_SB;
27 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_100_1_SB;
28 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_50_2_SB;
29 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_E_SB;
30 import static org.ops4j.pax.exam.CoreOptions.composite;
31 import static org.ops4j.pax.exam.CoreOptions.maven;
32 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
33
34 import com.google.common.collect.Lists;
35 import com.google.common.collect.Sets;
36 import com.google.common.net.InetAddresses;
37 import java.io.IOException;
38 import java.net.DatagramPacket;
39 import java.net.DatagramSocket;
40 import java.net.InetAddress;
41 import java.net.InetSocketAddress;
42 import java.net.SocketException;
43 import java.net.SocketTimeoutException;
44 import java.net.UnknownHostException;
45 import java.nio.ByteBuffer;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.List;
49 import java.util.Set;
50 import javax.inject.Inject;
51 import org.junit.After;
52 import org.junit.Assert;
53 import org.junit.Before;
54 import org.junit.Test;
55 import org.junit.runner.RunWith;
56 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
57 import org.opendaylight.lispflowmapping.config.ConfigIni;
58 import org.opendaylight.lispflowmapping.implementation.LispMappingService;
59 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
60 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
61 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
62 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
63 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
64 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
65 import org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer;
66 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
67 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
68 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
69 import org.opendaylight.lispflowmapping.lisp.util.ByteUtil;
70 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
71 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
72 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
73 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.AfiListLcaf;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ApplicationDataLcaf;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ExplicitLocatorPathLcaf;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.InstanceIdType;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.KeyValueAddressLcaf;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.MacAfi;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.Address;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiList;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationData;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4Prefix;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4PrefixBuilder;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.KeyValueAddress;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Mac;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.afi.list.AfiListBuilder;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.application.data.ApplicationDataBuilder;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.ExplicitLocatorPathBuilder;
98 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;
99 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;
100 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;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.source.dest.key.SourceDestKeyBuilder;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.Ipv4AddressBinary;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4BinaryBuilder;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinaryBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.OdlLispProtoListener;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.SiteId;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrId;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.EidBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkeyBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord.Action;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapregisternotification.MapRegisterBuilder;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRlocBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.SourceEidBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.RlocBuilder;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
143 import org.ops4j.pax.exam.Option;
144 import org.ops4j.pax.exam.junit.PaxExam;
145 import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
146 import org.ops4j.pax.exam.options.MavenUrlReference;
147 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
148 import org.ops4j.pax.exam.spi.reactors.PerClass;
149 import org.ops4j.pax.exam.util.Filter;
150 import org.osgi.framework.Bundle;
151 import org.osgi.framework.BundleContext;
152 import org.osgi.framework.InvalidSyntaxException;
153 import org.slf4j.Logger;
154 import org.slf4j.LoggerFactory;
155
156 @RunWith(PaxExam.class)
157 @ExamReactorStrategy(PerClass.class)
158 public class MappingServiceIntegrationTest extends AbstractMdsalTestBase {
159     private static final Logger LOG = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
160
161     /**
162      * Defines how many attempt to create instance of DatagramSocket will be done before giving up.
163      */
164     private static final int NUM_OF_ATTEMPTS_TO_CREATE_SOCKET = 2;
165
166     private byte[] mapRequestPacket;
167     private byte[] mapRegisterPacketWithNotify;
168     private byte[] mapRegisterPacketWithoutNotify;
169     String lispBindAddress = "127.0.0.1";
170     static final String ourAddress = "127.0.0.2";
171     private Rloc locatorEid;
172     private DatagramSocket socket;
173     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
174
175     public static final String ODL = "org.opendaylight.controller";
176     public static final String YANG = "org.opendaylight.yangtools";
177     private static final int MULTI_SITE_SLEEP_TIME = 1;
178     private static final int MAX_NOTIFICATION_RETRYS = 20;
179     private static final MappingAuthkey NULL_AUTH_KEY = new MappingAuthkeyBuilder().setKeyType(0).build();
180
181     // This is temporary, since the properties in the pom file are not picked up
182     @Override
183     public String getKarafDistro() {
184         return maven()
185                 .groupId("org.opendaylight.lispflowmapping")
186                 .artifactId("distribution-karaf")
187                 .versionAsInProject()
188                 .type("zip")
189                 .getURL();
190     }
191
192     @Override
193     public MavenUrlReference getFeatureRepo() {
194         return maven()
195                 .groupId("org.opendaylight.lispflowmapping")
196                 .artifactId("features-lispflowmapping")
197                 .classifier("features")
198                 .type("xml")
199                 .versionAsInProject();
200     }
201
202     @Override
203     public String getFeatureName() {
204         return "odl-lispflowmapping-msmr";
205     }
206
207     @Override
208     public Option getLoggingOption() {
209         Option option = editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
210                 "log4j.logger.org.opendaylight.lispflowmapping",
211                 LogLevel.DEBUG.name());
212         option = composite(option, super.getLoggingOption());
213         return option;
214     }
215
216     @Test
217     public void testLispFlowMappingFeatureLoad() {
218         Assert.assertTrue(true);
219     }
220
221     @After
222     public void after() {
223         if (socket != null) {
224             socket.close();
225         }
226         // reset mapping record validity to default value
227         ConfigIni.getInstance().setRegistrationValiditySb(200000L);
228     }
229
230     @Before
231     public void before() throws Exception {
232         areWeReady();
233         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_FIRST);
234         mapService.setMappingMerge(false);
235         ConfigIni.getInstance().setSmrRetryCount(1);
236
237         locatorEid = LispAddressUtil.asIpv4Rloc("4.3.2.1");
238         socket = initSocket(socket, LispMessage.PORT_NUM);
239
240         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
241         // LISP(Type = 8 - Encapsulated)
242         // IP: 192.168.136.10 -> 153.16.254.1
243         // UDP: 56756
244         // LISP(Type = 1 Map-Request
245         // Record Count: 1
246         // ITR-RLOC count: 0
247         // Source EID AFI: 1
248         // Source EID 1.2.3.4
249         // Nonce: 0x3d8d2acd39c8d608
250         // ITR-RLOC AFI=1 Address=192.168.136.10
251         // Record 1: 153.16.254.1/32
252         mapRequestPacket = extractWSUdpByteArray(new String("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 " //
253                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
254                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
255                 + "0030   00 3c d4 31 00 00 ff 11 56 f3 7f 00 00 02 99 10 "
256                 + "0040   fe 01 dd b4 10 f6 00 28 ef 3a 10 00 00 01 3d 8d "
257                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 " //
258                 + "0060   00 01 99 10 fe 01"));
259
260         // IP: 192.168.136.10 -> 128.223.156.35
261         // UDP: 49289 -> 4342
262         // LISP(Type = 3 Map-Register, P=1, M=1
263         // Record Counter: 1
264         // Nonce: 0
265         // Key ID: 0x0001
266         // AuthDataLength: 20 Data:
267         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
268         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
269         // No-Action
270         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
271         // Priority/Weight: 1/100, Multicast Priority/Weight:
272         // 255/0
273         //
274
275         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(new String(
276                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
277                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
278                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
279                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
280                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
281                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
282                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
283
284         // IP: 192.168.136.10 -> 128.223.156.35
285         // UDP: 49289 -> 4342
286         // LISP(Type = 3 Map-Register, P=1, M=1
287         // Record Counter: 1
288         // Nonce: 7
289         // Key ID: 0x0000 NO AUTHENTICATION!!
290         // AuthDataLength: 00 Data:
291         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
292         // No-Action
293         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
294         // Priority/Weight: 1/100, Multicast Priority/Weight:
295         // 255/0
296         //
297
298         mapRegisterPacketWithNotify = extractWSUdpByteArray(new String(
299                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
300                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
301                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
302                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
303                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
304                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
305                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
306
307         // IP: 192.168.136.10 -> 128.223.156.35
308         // UDP: 49289 -> 4342
309         // LISP(Type = 3 Map-Register, P=1, M=1
310         // Record Counter: 1
311         // Nonce: 7
312         // Key ID: 0x0000 NO AUTHENTICATION!!
313         // AuthDataLength: 00 Data:
314         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
315         // No-Action
316         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
317         // Priority/Weight: 1/100, Multicast Priority/Weight:
318         // 255/0
319         //
320
321         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(new String(
322                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 " //
323                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
324                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
325                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
326                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
327                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 " //
328                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a"));
329     }
330
331     @Inject
332     private BundleContext bc;
333     //private HttpURLConnection connection;
334     protected static boolean notificationCalled;
335
336     @Inject @Filter(timeout=60000)
337     private IFlowMapping lms;
338
339     @Inject @Filter(timeout=60000)
340     private IMappingService mapService;
341
342     @Inject @Filter(timeout=10000)
343     private IConfigLispSouthboundPlugin configLispPlugin;
344
345     @Test
346     public void testSimpleUsage() throws Exception {
347         mapRequestSimple();
348         mapRegisterWithMapNotify();
349         mapRegisterWithMapNotifyAndMapRequest();
350         registerAndQuery__MAC();
351         mapRequestMapRegisterAndMapRequest();
352         mapRegisterWithAuthenticationWithoutConfiguringAKey();
353         mapRegisterWithoutMapNotify();
354     }
355
356     @Test
357     public void testLCAFs() throws Exception {
358         registerAndQuery__SrcDestLCAF();
359         registerAndQuery__SrcDestLCAFOverlap();
360         registerAndQuery__KeyValueLCAF();
361         //registerAndQuery__ListLCAF();
362         //registerAndQuery__ApplicationData();
363         //registerAndQuery__TrafficEngineering();
364         //registerAndQuery__SegmentLCAF();
365     }
366
367     @Test
368     public void testMask() throws Exception {
369         //testPasswordExactMatch();                     TODO commented because it needs NB
370         //testPasswordMaskMatch();                      TODO commented because it needs NB
371         eidPrefixLookupIPv4();
372         eidPrefixLookupIPv6();
373     }
374 /*
375     @Test
376     public void testNorthbound() throws Exception {
377         northboundAddKey();
378         northboundAddMapping();
379         northboundDeleteMapping();
380         northboundRetrieveKey();
381         northboundRetrieveMapping();
382         northboundRetrieveSourceDestKey();
383         northboundRetrieveSourceDestMapping();
384     }
385 */
386     @Test
387     public void testOverWriting() throws Exception {
388         //testMapRegisterDosntOverwritesOtherSubKeys(); TODO weird failure, needs debug
389
390         // TODO: remove, we don't support overwrite flag any longer and RLOCs are not saved as independent RLOC groups
391         // testMapRegisterOverwritesSameSubkey();
392         // testMapRegisterOverwritesNoSubkey();
393         // testMapRegisterDoesntOverwritesNoSubkey();
394     }
395
396     @Test
397     public void testTimeOuts() throws Exception {
398         timedOutMappingRecord();
399         mapRequestMapRegisterAndMapRequestTestTimeout();
400         //mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();   TODO commented because it needs NB
401     }
402
403 //    @Test
404 //    public void testNonProxy() throws Throwable {
405 //        testSimpleNonProxy();
406 //        testNonProxyOtherPort();
407 //        testRecievingNonProxyOnXtrPort();
408 //    }
409
410     @Test
411     public void testSmr() throws Exception {
412         registerQueryRegisterWithSmr();
413         testRepeatedSmr();
414     }
415
416     @Test
417     public void testMultiSite() throws Exception {
418         testMultiSiteScenarioA();
419         testMultiSiteScenarioB();
420     }
421
422     @Test
423     public void testNegativePrefix_gapIntersection() throws UnknownHostException {
424         insertMappings();
425         testGapIntersection();
426
427         insertMappings();
428         testMultipleMappings();
429     }
430
431     private void testRepeatedSmr() throws SocketTimeoutException, UnknownHostException {
432         cleanUP();
433         long timeout = ConfigIni.getInstance().getSmrTimeout();
434         ConfigIni.getInstance().setSmrRetryCount(5);
435
436         final InstanceIdType iid = new InstanceIdType(1L);
437         final Eid eid1 = LispAddressUtil.asIpv4Eid("1.1.1.1", 1L);
438         final int expectedSmrs1 = 2;
439         final int expectedSmrs2 = 3;
440
441         /* set auth */
442         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iid);
443         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
444
445         /* add subscribers */
446         final String subscriberSrcRloc1 = "127.0.0.3";
447         final String subscriberSrcRloc2 = "127.0.0.4";
448         final Set<Subscriber> subscriberSet1 = Sets.newHashSet(newSubscriber(eid1, subscriberSrcRloc1),
449                 newSubscriber(eid1, subscriberSrcRloc2));
450         mapService.addData(MappingOrigin.Southbound, eid1, SubKeys.SUBSCRIBERS, subscriberSet1);
451
452         final SocketReader reader1 = startSocketReader(subscriberSrcRloc1, 15000);
453         final SocketReader reader2 = startSocketReader(subscriberSrcRloc2, 15000);
454         sleepForSeconds(1);
455
456         /* add mapping */
457         final MappingRecord mapping1 = new MappingRecordBuilder()
458                 .setEid(eid1).setTimestamp(System.currentTimeMillis()).setRecordTtl(1440).build();
459         mapService.addMapping(MappingOrigin.Northbound, eid1, null, new MappingData(mapping1));
460
461         sleepForMilliseconds((timeout * expectedSmrs1) - (timeout / 2));
462         final List<MapRequest> requests1 = processSmrPackets(reader1, subscriberSrcRloc1, expectedSmrs1);
463         final MapReply mapReply1 = lms.handleMapRequest(
464                 new MapRequestBuilder(requests1.get(0))
465                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
466                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc1)).build()))
467                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
468                         .setSmrInvoked(true)
469                         .setSmr(false).build());
470
471         // sleep to get 1 extra smr request
472         sleepForMilliseconds(timeout * 1);
473         final List<MapRequest> requests2 = processSmrPackets(reader2, subscriberSrcRloc2, expectedSmrs2);
474         final MapReply mapReply2 = lms.handleMapRequest(
475                 new MapRequestBuilder(requests2.get(0))
476                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
477                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc2)).build()))
478                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
479                         .setSmrInvoked(true)
480                         .setSmr(false).build());
481
482         sleepForSeconds(3);
483         assertEquals(expectedSmrs1, requests1.size());
484         assertEquals(expectedSmrs2, requests2.size());
485         assertEquals((long) mapReply1.getNonce(), (long) requests1.get(0).getNonce());
486         assertEquals((long) mapReply2.getNonce(), (long) requests2.get(0).getNonce());
487         assertNextBufferEmpty(reader1);
488         assertNextBufferEmpty(reader2);
489
490         reader1.stopReading();
491         reader2.stopReading();
492     }
493
494     private SocketReader startSocketReader(String address, int timeout) {
495         DatagramSocket receivingSocket = null;
496
497         try {
498             receivingSocket = new DatagramSocket(new InetSocketAddress(address, LispMessage.PORT_NUM));
499         } catch (SocketException e) {
500             LOG.error("Can't initialize socket for {}", address, e);
501         }
502         return SocketReader.startReadingInStandaloneThread(receivingSocket, timeout);
503     }
504
505     private List<MapRequest> processSmrPackets(SocketReader reader, String address, int expectedSmrs) {
506         InetAddress inetAddress = null;
507         try {
508             inetAddress = InetAddress.getByName(address);
509         } catch (UnknownHostException e) {
510             LOG.error("Unknown address {}.", address, e);
511         }
512
513         final List<MapRequest> requests = Lists.newArrayList();
514         byte[][] buffers = reader.getBuffers(expectedSmrs);
515         for (byte[] buf : buffers) {
516             MapRequest request = MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(buf), inetAddress);
517             requests.add(request);
518         }
519         return requests;
520     }
521
522     private void assertNextBufferEmpty(SocketReader socketReader) {
523         assertTrue(isArrayEmpty(socketReader.getBuffers(1)[0]));
524     }
525
526     private boolean isArrayEmpty(byte[] byteArray) {
527         for (byte b : byteArray) {
528             if (b != 0) {
529                 return false;
530             }
531         }
532         return true;
533     }
534
535     private static Subscriber newSubscriber(Eid srcEid, String srcRlocIp) {
536         final byte[] addressBinary = InetAddresses.forString(srcRlocIp).getAddress();
537         final int timeout = 5;
538         final Rloc srcRloc = new RlocBuilder().setAddress(new Ipv4BinaryBuilder()
539                 .setIpv4Binary(new Ipv4AddressBinary(addressBinary)).build()).build();
540
541         return new Subscriber(srcRloc, srcEid, timeout);
542     }
543
544     private void testMultipleMappings() throws UnknownHostException {
545         final InstanceIdType iid = new InstanceIdType(1L);
546         final String prefix1 = "1.1.127.10/32"; // prefix from the intersection of NB and SB gaps
547         final String prefix2 = "1.1.200.255/32"; // prefix with existing mapping in NB
548         final String prefix3 = "1.3.255.255/32";
549
550         final MapRequest mapRequest = new MapRequestBuilder().setSmrInvoked(false).setEidItem(Lists.newArrayList(
551                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix1, iid))
552                         .build(),
553                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix2, iid))
554                         .build(),
555                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix3, iid))
556                         .build()))
557                 .build();
558         final MapReply mapReply = lms.handleMapRequest(mapRequest);
559
560         // expected result
561         final String resultPrefix1 = "1.1.64.0";
562         final Address resultNegMapping1 = new Ipv4PrefixBinaryBuilder()
563                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix1).getAddress()))
564                 .setIpv4MaskLength((short) 18).build();
565
566         final String resultPrefix2 = "1.1.128.0";
567         final Address resultMapping2 = new Ipv4PrefixBinaryBuilder()
568                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix2).getAddress()))
569                 .setIpv4MaskLength((short) 17).build();
570
571         final String resultPrefix3 = "1.3.0.0";
572         final Address resultNegMapping3 = new Ipv4PrefixBinaryBuilder()
573                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix3).getAddress()))
574                 .setIpv4MaskLength((short) 16).build();
575
576         assertEquals(resultNegMapping1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
577                 .getAddress());
578         assertEquals(resultMapping2, mapReply.getMappingRecordItem().get(1).getMappingRecord().getEid()
579                 .getAddress());
580         assertEquals(resultNegMapping3, mapReply.getMappingRecordItem().get(2).getMappingRecord().getEid()
581                 .getAddress());
582     }
583
584     /**
585      * Tests a negative mapping from an intersection of gaps in northbound and southbound.
586      */
587     private void testGapIntersection() throws UnknownHostException {
588         final InstanceIdType iid = new InstanceIdType(1L);
589
590         // request an Eid from a gap between mappings
591         final MapRequest mapRequest = new MapRequestBuilder().setSmrInvoked(false).setEidItem(Lists.newArrayList(
592                 new EidItemBuilder().setEid(LispAddressUtil.asIpv4PrefixBinaryEid("1.1.127.10/32", iid))
593                         .build()))
594                 .build();
595         final MapReply mapReply = lms.handleMapRequest(mapRequest);
596
597         // expected negative mapping
598         final Address resultNegMapping = new Ipv4PrefixBinaryBuilder()
599                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName("1.1.64.0").getAddress()))
600                 .setIpv4MaskLength((short) 18).build();
601         assertEquals(resultNegMapping, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
602                 .getAddress());
603     }
604
605     private void insertMappings() {
606         cleanUP();
607         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
608
609         final InstanceIdType iid = new InstanceIdType(1L);
610         final String prefixNbLeft = "1.2.0.0/16";
611         final String prefixNbRight = "1.1.128.0/17";
612         final String prefixSbLeft = "1.1.32.0/19";
613         final String prefixSbRight = "1.0.0.0/8";
614
615         final MappingRecord mapRecordNbLeft = newMappingRecord(prefixNbLeft, iid);
616         final MappingRecord mapRecordNbRight = newMappingRecord(prefixNbRight, iid);
617         final MappingRecord mapRecordSbLeft = newMappingRecord(prefixSbLeft, iid);
618         final MappingRecord mapRecordSbRight = newMappingRecord(prefixSbRight, iid);
619
620         /* set auth */
621         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iid);
622         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
623
624         mapService.addMapping(MappingOrigin.Northbound, mapRecordNbLeft.getEid(), null,
625                 new MappingData(mapRecordNbLeft));
626         mapService.addMapping(MappingOrigin.Northbound, mapRecordNbRight.getEid(), null,
627                 new MappingData(mapRecordNbRight));
628         mapService.addMapping(MappingOrigin.Southbound, mapRecordSbLeft.getEid(), null,
629                 new MappingData(mapRecordSbLeft, System.currentTimeMillis()));
630         mapService.addMapping(MappingOrigin.Southbound, mapRecordSbRight.getEid(), null,
631                 new MappingData(mapRecordSbRight, System.currentTimeMillis()));
632
633         restartSocket();
634         sleepForSeconds(2);
635     }
636
637     /**
638      * Creates a new MappingRecord object.
639      *
640      * @param prefix The Eid prefix
641      * @param iid VNI
642      * @return new MappingRecord object
643      */
644     private MappingRecord newMappingRecord(String prefix, InstanceIdType iid) {
645         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iid);
646         return new MappingRecordBuilder()
647                 .setEid(prefixBinary)
648                 .setLocatorRecord(Lists.newArrayList(new LocatorRecordBuilder()
649                         .setRloc(LispAddressUtil.asIpv4Rloc("2.2.2.2"))
650                         .setLocatorId("loc_id")
651                         .setPriority((short) 1).build()))
652                 .setTimestamp(System.currentTimeMillis())
653                 .setRecordTtl(1440).build();
654     }
655
656     /**
657      * TEST SCENARIO A
658      */
659     public void testMultiSiteScenarioA() throws IOException {
660         cleanUP();
661         ConfigIni.getInstance().setSmrRetryCount(1);
662
663         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
664         multiSiteScenario.setCommonAuthentication();
665
666         restartSocket();
667         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
668
669         //TEST CASE 1
670         multiSiteScenario.storeSouthboundMappings(false, SITE_A, SITE_B, SITE_C, SITE_D4, SITE_D5);
671         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
672         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
673         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
674         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
675         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
676         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
677
678         //TEST CASE 2
679         //following action should trigger generatting of SMR messages:
680         // 1) 192.0.2.5/32
681         // 2) 192.0.1.1/32
682         multiSiteScenario.storeNorthMappingSrcDst(SITE_A, SITE_C);
683         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
684         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1));
685         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
686         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
687         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
688
689         //TEST CASE 3
690         // following action should trigger generatting of SMR messages:
691         // 1) 192.0.2.5/32
692         // 2) 192.0.1.1/32
693         // 3) 192.0.1.5/32
694         // 4) 192.0.4.5/32
695         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
696         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
697         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1), SITE_A
698                         .getHost(5),
699                 SITE_D4.getHost(5));
700         multiSiteScenario.assertPingWorks(SITE_D4, 5, SITE_C, 4);
701
702         //TEST CASE 4
703         // following action should trigger generatting of SMR messages:
704         // 1) 192.0.4.5/32
705         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C_RLOC_10);
706         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
707         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D4.getHost(5));
708         //way of testing ping - get RLOC for mapping src-dst and compare it with awaited value doesn't test
709         //that ping won't be successfull
710         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
711
712         //TEST CASE 5
713         // following action should trigger generatting of SMR messages:
714         // 1) 192.0.4.5/32
715         // 2) 192.0.2.5/32
716         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
717         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
718         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D4.getHost(5), SITE_B.getHost(5));
719         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
720
721         //TEST CASE 6
722         multiSiteScenario.assertPingFails(SITE_D5, 5, SITE_C, 3);
723
724         //TEST CASE 7
725         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A, SITE_C);
726         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
727         // following action should trigger generatting of SMR messages:
728         // 1) 192.0.4.5/32
729         // 2) 192.0.2.5/32
730         // 3) 192.0.5.5/32
731         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
732                 SITE_B.getHost(5));
733
734         // following action should trigger generatting of SMR messages:
735         // 1) 192.0.4.5/32
736         // 2) 192.0.2.5/32
737         // 3) 192.0.5.5/32
738         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
739         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
740         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
741                 SITE_B.getHost(5));
742
743         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
744         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
745         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
746
747         //TEST CASE 8
748         // following action should trigger generatting of SMR messages:
749         // 1) 192.0.4.5/32
750         // 2) 192.0.2.5/32
751         // 3) 192.0.5.5/32
752         // 4) 192.0.1.1/32
753         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B, SITE_C);
754         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
755         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
756                 SITE_B.getHost(5),
757                 SITE_A.getHost(1));
758         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
759         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
760         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
761
762         //TEST CASE 9
763         // following action should trigger generatting of SMR messages:
764         // 1) 192.0.4.5/32
765         // 2) 192.0.2.5/32
766         // 3) 192.0.5.5/32
767         // 4) 192.0.1.1/32
768         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
769         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
770         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
771                 SITE_B.getHost(5),
772                 SITE_A.getHost(1));
773         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
774         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
775         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
776
777         socketReader.stopReading();
778
779     }
780
781     /**
782      * TEST SCENARIO B
783      */
784     public void testMultiSiteScenarioB() throws IOException {
785         cleanUP();
786
787         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
788         multiSiteScenario.setCommonAuthentication();
789
790         restartSocket();
791         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
792
793         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
794         mapService.setMappingMerge(true);
795
796         //TEST CASE 1
797         multiSiteScenario.storeSouthboundMappings(true, SITE_A_SB, SITE_B_SB, SITE_C_WP_100_1_SB, SITE_D_WP_100_1_SB,
798                 SITE_E_SB);
799         multiSiteScenario.storeNorthMappingIpPrefix(SITE_A_SB);
800         multiSiteScenario.storeNorthMappingIpPrefix(SITE_B_SB);
801         multiSiteScenario.storeNorthMappingIpPrefix(SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
802         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
803         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
804         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
805
806         //TEST CASE 2
807         // following action should trigger generatting of SMR messages:
808         // 1) 192.0.2.5/32
809         // 2) 192.0.1.5/32
810         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
811         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
812         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
813
814         // following action should trigger generatting of SMR messages:
815         // 1) 192.0.2.5/32
816         // 2) 192.0.1.5/32
817         multiSiteScenario.storeNorthMappingNegative(SITE_C_SB, Action.Drop);
818         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
819         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
820
821         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
822         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_SB, 4);
823
824
825         //TEST CASE 3
826         // following action should trigger generatting of SMR messages:
827         // 1) 192.0.2.5/32
828         // 2) 192.0.1.5/32
829         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
830         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
831         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
832         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4);
833
834         //TEST CASE 4
835         multiSiteScenario.storeNorthMappingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
836         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
837         // following action should trigger generatting of SMR messages:
838         // 1) 192.0.2.5/32
839         // 2) 192.0.1.5/32
840         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
841         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
842
843         //TEST CASE 5
844         multiSiteScenario.deleteSouthboundMappings(SITE_D_DELETE_SB);
845         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
846         // following action should trigger generatting of SMR messages:
847         // 1) 192.0.2.5/32
848         // 2) 192.0.1.5/32
849         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
850
851         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
852
853         //TEST CASE 6
854         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
855         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
856         // following action should trigger generatting of SMR messages:
857         // 1) 192.0.2.5/32
858         // 2) 192.0.1.5/32
859         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
860
861         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB);
862         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
863         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
864
865         socketReader.stopReading();
866
867     }
868
869     // ------------------------------- Simple Tests ---------------------------
870
871     public void mapRequestSimple() throws SocketTimeoutException {
872         cleanUP();
873
874         // This Map-Request is sent from a source port different from 4342
875         // We close and bind the socket on the correct port
876         if (socket != null) {
877             socket.close();
878         }
879         socket = initSocket(socket, 56756);
880
881         sendPacket(mapRequestPacket);
882         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
883         MapReply reply = MapReplySerializer.getInstance().deserialize(readBuf);
884         assertEquals(4435248268955932168L, reply.getNonce().longValue());
885
886     }
887
888     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
889         cleanUP();
890         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
891
892         sleepForSeconds(2);
893         sendPacket(mapRegisterPacketWithNotify);
894         MapNotify reply = receiveMapNotify();
895         assertEquals(7, reply.getNonce().longValue());
896     }
897
898     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
899         cleanUP();
900         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
901
902         MapReply mapReply = registerAddressAndQuery(eid);
903
904         assertEquals(4, mapReply.getNonce().longValue());
905         assertEquals(locatorEid, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
906                 .getRloc());
907
908     }
909
910     public void registerAndQuery__MAC() throws SocketTimeoutException {
911         cleanUP();
912         String macAddress = "01:02:03:04:05:06";
913
914         MapReply reply = registerAddressAndQuery(LispAddressUtil.asMacEid(macAddress));
915
916         assertTrue(true);
917         Eid addressFromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
918         assertEquals(MacAfi.class, addressFromNetwork.getAddressType());
919         String macAddressFromReply = ((Mac) addressFromNetwork.getAddress()).getMac().getValue();
920
921         assertEquals(macAddress, macAddressFromReply);
922     }
923
924     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
925         cleanUP();
926         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
927         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
928         sleepForSeconds(1);
929
930         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
931         mapRequestBuilder.setNonce((long) 4);
932         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
933         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
934         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
935         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
936         mapRequestBuilder.getItrRloc().add(
937                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
938         sendMapRequest(mapRequestBuilder.build());
939         MapReply mapReply = receiveMapReply();
940         assertEquals(4, mapReply.getNonce().longValue());
941         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
942         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
943         mapRegisterbuilder.setWantMapNotify(true);
944         mapRegisterbuilder.setNonce((long) 8);
945         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
946         etlrBuilder.setEid(eid);
947         etlrBuilder.setRecordTtl(254);
948         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
949         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
950         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
951         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
952         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
953         mapRegisterbuilder.getMappingRecordItem().add(
954                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
955         sendMapRegister(mapRegisterbuilder.build());
956         MapNotify mapNotify = receiveMapNotify();
957         assertEquals(8, mapNotify.getNonce().longValue());
958         sleepForSeconds(1);
959         sendMapRequest(mapRequestBuilder.build());
960         mapReply = receiveMapReply();
961         assertEquals(4, mapReply.getNonce().longValue());
962         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
963                 .getLocatorRecord().get(0).getRloc());
964
965     }
966
967     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
968         cleanUP();
969         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
970         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
971         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
972         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
973         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
974         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
975         assertEquals(2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
976         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
977                 .getRloc());
978         assertEquals(rloc1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1)
979                 .getRloc());
980     }
981
982     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
983         cleanUP();
984         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
985         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
986         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
987         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
988         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
989         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
990         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
991         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
992                 .getRloc());
993     }
994
995     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
996         cleanUP();
997         mapService.setMappingMerge(false);
998         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
999         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1000         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1001         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1002         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1003         assertEquals(rloc2Value, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1004                 .getRloc());
1005     }
1006
1007     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
1008         cleanUP();
1009         mapService.setMappingMerge(true);
1010         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1011         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1012         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1013         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1014         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1015         Rloc rloc1ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1016                 .get(0).getRloc();
1017         Rloc rloc2ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1018                 .get(1).getRloc();
1019         assertTrue((rloc1Value.equals(rloc1ReturnValueContainer) && rloc2Value.equals(rloc2ReturnValueContainer))
1020                 || (rloc1Value.equals(rloc2ReturnValueContainer) && rloc2Value.equals(rloc1ReturnValueContainer)));
1021     }
1022
1023     private MapReply sendMapRegisterTwiceWithDiffrentValues(Eid eid, Rloc rloc1, Rloc rloc2)
1024             throws SocketTimeoutException {
1025         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1026         sleepForSeconds(1);
1027         MapRegister mb = createMapRegister(eid, rloc1);
1028         MapNotify mapNotify = lms.handleMapRegister(mb).getLeft();
1029         MapRequest mr = createMapRequest(eid);
1030         MapReply mapReply = lms.handleMapRequest(mr);
1031         assertEquals(mb.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc(),
1032                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1033         mb = createMapRegister(eid, rloc2);
1034         mapNotify = lms.handleMapRegister(mb).getLeft();
1035         assertEquals(8, mapNotify.getNonce().longValue());
1036         mr = createMapRequest(eid);
1037         sendMapRequest(mr);
1038         mapReply = lms.handleMapRequest(mr);
1039         return mapReply;
1040     }
1041
1042     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
1043         cleanUP();
1044         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
1045         try {
1046             receivePacket(3000);
1047             // If didn't timeout then fail:
1048             fail();
1049         } catch (SocketTimeoutException ste) {
1050         }
1051     }
1052
1053     public void mapRegisterWithoutMapNotify() {
1054         cleanUP();
1055         sendPacket(mapRegisterPacketWithoutNotify);
1056         try {
1057             receivePacket(3000);
1058             // If didn't timeout then fail:
1059             fail();
1060         } catch (SocketTimeoutException ste) {
1061         }
1062     }
1063
1064     public void registerQueryRegisterWithSmr() throws SocketTimeoutException {
1065         cleanUP();
1066         lms.setShouldUseSmr(true);
1067         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
1068         sleepForSeconds(1);
1069
1070         sendPacket(mapRegisterPacketWithNotify);
1071         receiveMapNotify();
1072
1073         sleepForSeconds(1);
1074         sendPacket(mapRequestPacket);
1075         sleepForSeconds(1);
1076
1077         mapRegisterPacketWithoutNotify[mapRegisterPacketWithoutNotify.length - 1] += 1;
1078         sendPacket(mapRegisterPacketWithoutNotify);
1079
1080         ByteBuffer readBuf = ByteBuffer.wrap(receivePacket().getData());
1081         MapRequest smr = MapRequestSerializer.getInstance().deserialize(readBuf, null);
1082         assertTrue(smr.isSmr());
1083         Eid sourceEid = smr.getSourceEid().getEid();
1084         assertTrue(LispAddressUtil.asIpv4Eid("153.16.254.1").equals(sourceEid));
1085         Eid smrEid = smr.getEidItem().get(0).getEid();
1086         assertTrue(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32").equals(smrEid));
1087     }
1088
1089     // --------------------- Northbound Tests ---------------------------
1090 /*
1091     private void northboundAddKey() throws Exception {
1092         cleanUP();
1093         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("1.2.3.4");
1094         int mask = 32;
1095         String pass = "asdf";
1096
1097         URL url = createPutURL("key");
1098         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
1099         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
1100
1101         String retrievedKey = lms.getAuthenticationKey(LispAddressUtil.toContainer(address), mask);
1102
1103         // Check stored password matches the one sent
1104         assertEquals(pass, retrievedKey);
1105
1106     }
1107
1108     private void northboundRetrieveSourceDestKey() throws Exception {
1109         cleanUP();
1110         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1111                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1112                 .primitiveaddress.Ipv4) LispAddressUtil
1113                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1114         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1115                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1116                 .primitiveaddress.Ipv4) LispAddressUtil
1117                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1118         int mask1 = 32;
1119         int mask2 = 32;
1120         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1121                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1122                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1123                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build())
1124                 .setSrcMaskLength((short) mask1)
1125                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build())
1126                 .setDstMaskLength((short) mask2).build();
1127         String pass = "asdf";
1128
1129         lms.addAuthenticationKey(LispAddressUtil.toContainer(sourceDestAddress), mask1, pass);
1130
1131         // URL url = createGetKeyIPv4URL(address1, mask1);
1132         URL url = createGetKeySourceDestURL(address1.getIpv4Address().getAfi(),
1133                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getSrcAddress()
1134                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(),
1135                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getDstAddress()
1136                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
1137         String reply = callURL("GET", null, "application/json", null, url);
1138         JSONTokener jt = new JSONTokener(reply);
1139         JSONObject json = new JSONObject(jt);
1140
1141         // test that the password matches what was we expected.
1142         assertEquals(pass, json.get("key"));
1143
1144     }
1145
1146     private void northboundRetrieveKey() throws Exception {
1147         cleanUP();
1148         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1149         int mask = 32;
1150         String pass = "asdf";
1151
1152         lms.addAuthenticationKey(LispAddressUtil.toContainer(address), mask, pass);
1153
1154         URL url = createGetKeyIPv4URL(address, mask);
1155         String reply = callURL("GET", null, "application/json", null, url);
1156         JSONTokener jt = new JSONTokener(reply);
1157         JSONObject json = new JSONObject(jt);
1158
1159         // test that the password matches what was we expected.
1160         assertEquals(pass, json.get("key"));
1161
1162     }
1163
1164     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
1165         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
1166                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
1167     }
1168
1169     private void northboundAddMapping() throws Exception {
1170         cleanUP();
1171         String pass = "asdf";
1172         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1173         int mask = 32;
1174         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1175
1176         // NB add mapping always checks the key
1177         lms.addAuthenticationKey(LispAddressUtil.toContainer(eid), mask, pass);
1178
1179         URL url = createPutURL("mapping");
1180         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
1181         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
1182
1183         // Retrieve the RLOC from the database
1184         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1185         mapRequestBuilder.setPitr(false);
1186         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1187         mapRequestBuilder.getEidItem().add(
1188                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(
1189                 LispAddressUtil.toContainer(eid)).build());
1190         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
1191
1192         LispIpv4Address retrievedRloc = (LispIpv4Address) LispAddressUtil.toAFI(
1193                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1194                 .getLispAddressContainer());
1195
1196         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
1197
1198     }
1199
1200     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
1201         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ "
1202                 + "\"proxyMapReply\" : false, "
1203                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : "
1204                 + "{ " + "\"ipAddress\" : \""
1205                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "},"
1206                 + "\"mapVersion\" : 0,"
1207                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ "
1208                 + "\"multicastPriority\" : 1,"
1209                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\","
1210                 + "\"afi\" : "
1211                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50,"
1212                 + "\"rlocProbed\" : false, "
1213                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], "
1214                 + "\"recordTtl\" : 100" + "} " + "], "
1215                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
1216
1217         return jsonString;
1218     }
1219
1220     private void northboundRetrieveMapping() throws Exception {
1221         cleanUP();
1222         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1223         int mask = 32;
1224         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1225         // Insert mapping in the database
1226         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1227         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1228         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1229         etlr.setMaskLength((short) mask);
1230         etlr.setRecordTtl(254);
1231         etlr.setAuthoritative(false);
1232         etlr.setAction(Action.NoAction);
1233         LocatorRecordBuilder record = new LocatorRecordBuilder();
1234         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1235         record.setRouted(true);
1236         record.setRlocProbed(false);
1237         record.setLocalLocator(false);
1238         record.setPriority((short) 1);
1239         record.setWeight((short) 50);
1240         record.setMulticastPriority((short) 1);
1241         record.setMulticastWeight((short) 1);
1242         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1243         etlr.getLocatorRecord().add(record.build());
1244         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1245         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1246         lms.handleMapRegister(mapRegister.build());
1247
1248         // Get mapping using NB interface. No IID used
1249         URL url = createGetMappingIPv4URL(0, eid, mask);
1250         String reply = callURL("GET", null, "application/json", null, url);
1251         JSONTokener jt = new JSONTokener(reply);
1252         JSONObject json = new JSONObject(jt);
1253
1254         // With just one locator, locators is not a JSONArray
1255         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
1256                 .getString("ipAddress");
1257
1258         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
1259
1260     }
1261
1262     private void northboundDeleteMapping() throws Exception {
1263         cleanUP();
1264         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1265         int mask = 32;
1266         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1267         // Insert mapping in the database
1268         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1269         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1270         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1271         etlr.setMaskLength((short) mask);
1272         etlr.setRecordTtl(254);
1273         etlr.setAuthoritative(false);
1274         etlr.setAction(Action.NoAction);
1275         LocatorRecordBuilder record = new LocatorRecordBuilder();
1276         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1277         record.setRouted(true);
1278         record.setRlocProbed(false);
1279         record.setLocalLocator(false);
1280         record.setPriority((short) 1);
1281         record.setWeight((short) 50);
1282         record.setMulticastPriority((short) 1);
1283         record.setMulticastWeight((short) 1);
1284         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1285         etlr.getLocatorRecord().add(record.build());
1286         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1287         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1288         lms.handleMapRegister(mapRegister.build());
1289
1290         // Delete mapping using NB interface. No IID used
1291         URL url = createDeleteMappingIPv4URL(0, eid, mask);
1292         String reply = callURL("DELETE", null, "application/json", null, url);
1293
1294         // Get mapping using NB interface. No IID used
1295         url = createGetMappingIPv4URL(0, eid, mask);
1296         reply = callURL("GET", null, "application/json", null, url);
1297         JSONTokener jt = new JSONTokener(reply);
1298         JSONObject json = new JSONObject(jt);
1299
1300         // With just one locator, locators is not a JSONArray
1301         assertEquals(json.getJSONArray("locators").length(), 0);
1302     }
1303
1304     private void northboundRetrieveSourceDestMapping() throws Exception {
1305         cleanUP();
1306         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1307                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1308                 .primitiveaddress.Ipv4) LispAddressUtil
1309                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1310         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1311                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1312                 .primitiveaddress.Ipv4) LispAddressUtil
1313                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1314         int mask1 = 32;
1315         int mask2 = 32;
1316         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1317                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1318                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1319                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(
1320                         address1).build()).setSrcMaskLength((short) mask1)
1321                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(
1322                         address2).build()).setDstMaskLength((short) mask2).build();
1323         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1324
1325         // Insert mapping in the database
1326         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1327         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1328         etlr.setLispAddressContainer(LispAddressUtil.toContainer(sourceDestAddress));
1329         etlr.setMaskLength((short) mask1);
1330         etlr.setRecordTtl(254);
1331         etlr.setAuthoritative(false);
1332         etlr.setAction(Action.NoAction);
1333         LocatorRecordBuilder record = new LocatorRecordBuilder();
1334         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
1335         record.setRouted(true);
1336         record.setRlocProbed(false);
1337         record.setLocalLocator(false);
1338         record.setPriority((short) 1);
1339         record.setWeight((short) 50);
1340         record.setMulticastPriority((short) 1);
1341         record.setMulticastWeight((short) 1);
1342         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1343         etlr.getLocatorRecord().add(record.build());
1344         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1345         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1346         lms.handleMapRegister(mapRegister.build());
1347
1348         // Get mapping using NB interface. No IID used
1349         URL url = createGetMappingSourceDestURL(address1.getIpv4Address().getAfi(),
1350                 address1.getIpv4Address().getIpv4Address().getValue(),
1351                 mask1,
1352                 address2.getIpv4Address().getIpv4Address().getValue(),
1353                 mask2);
1354         String reply = callURL("GET", null, "application/json", null, url);
1355         JSONTokener jt = new JSONTokener(reply);
1356         JSONObject json = new JSONObject(jt);
1357
1358         // With just one locator, locators is not a JSONArray
1359         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
1360         .getString("ipAddress");
1361
1362         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
1363
1364     }
1365
1366     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
1367         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key",
1368                 address.getAfi().shortValue(),
1369                 address.getIpv4Address().getValue(), mask);
1370         URL url = new URL(restUrl);
1371         return url;
1372     }
1373
1374     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
1375             throws MalformedURLException {
1376         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
1377                 "key", afi, srcAddress, srcMask,
1378                 dstAddress, dstMask);
1379         URL url = new URL(restUrl);
1380         return url;
1381     }
1382
1383     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
1384             throws MalformedURLException {
1385         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
1386                 "mapping", afi, srcAddress,
1387                 srcMask, dstAddress, dstMask);
1388         URL url = new URL(restUrl);
1389         return url;
1390     }
1391
1392     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
1393         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
1394                 iid, address.getAfi()
1395                 .shortValue(), address.getIpv4Address().getValue(), mask);
1396         URL url = new URL(restUrl);
1397         return url;
1398     }
1399
1400     private URL createDeleteMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
1401         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
1402                 iid, address.getAfi()
1403                 .shortValue(), address.getIpv4Address().getValue(), mask);
1404         URL url = new URL(restUrl);
1405         return url;
1406     }
1407
1408     private URL createPutURL(String resource) throws MalformedURLException {
1409
1410         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
1411
1412         URL url = new URL(restUrl);
1413         return url;
1414     }
1415
1416     private String createAuthenticationString() {
1417         String authString = "admin:admin";
1418         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
1419         String authStringEnc = new String(authEncBytes);
1420         return authStringEnc;
1421     }
1422
1423     private String callURL(String method, String content, String accept, String body, URL url) throws IOException,
1424             JSONException {
1425         String authStringEnc = createAuthenticationString();
1426         connection = (HttpURLConnection) url.openConnection();
1427         connection.setRequestMethod(method);
1428         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
1429         if (content != null) {
1430             connection.setRequestProperty("Content-Type", content);
1431         }
1432         if (accept != null) {
1433             connection.setRequestProperty("Accept", accept);
1434         }
1435         if (body != null) {
1436             // now add the request body
1437             connection.setDoOutput(true);
1438             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
1439             wr.write(body);
1440             wr.flush();
1441         }
1442         connection.connect();
1443
1444         // getting the result, first check response code
1445         Integer httpResponseCode = connection.getResponseCode();
1446
1447         if (httpResponseCode > 299) {
1448             LOG.trace("HTTP Address: " + url);
1449             LOG.trace("HTTP Response Code: " + httpResponseCode);
1450             fail();
1451         }
1452
1453         InputStream is = connection.getInputStream();
1454         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
1455         StringBuilder sb = new StringBuilder();
1456         int cp;
1457         while ((cp = rd.read()) != -1) {
1458             sb.append((char) cp);
1459         }
1460         is.close();
1461         connection.disconnect();
1462         return (sb.toString());
1463     }
1464
1465     // timePeriod - in ms
1466     public void assertNoPacketReceived(int timePeriod) {
1467         try {
1468             receivePacket(timePeriod);
1469             // If didn't timeout then fail:
1470             fail();
1471         } catch (SocketTimeoutException ste) {
1472         }
1473     }
1474 */
1475     // ------------------------------- Mask Tests ---------------------------
1476
1477     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
1478         cleanUP();
1479         runPrefixTest(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/16"),
1480                 LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.2/32"),
1481                 LispAddressUtil.asIpv4PrefixBinaryEid("1.1.1.1/32"));
1482     }
1483
1484     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
1485         cleanUP();
1486         runPrefixTest(LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:6:7:8/64"),
1487                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:1:2:3/128"),
1488                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:1:2:3:1:2/128"));
1489     }
1490
1491     private void runPrefixTest(Eid registerEID, Eid matchedAddress, Eid unMatchedAddress)
1492             throws SocketTimeoutException {
1493         mapService.addAuthenticationKey(registerEID, NULL_AUTH_KEY);
1494         sleepForSeconds(1);
1495
1496         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1497         mapRegister.setWantMapNotify(true);
1498         mapRegister.setNonce((long) 8);
1499         mapRegister.setWantMapNotify(true);
1500         mapRegister.setKeyId((short) 0);
1501         mapRegister.setAuthenticationData(new byte[0]);
1502         mapRegister.setNonce((long) 8);
1503         mapRegister.setProxyMapReply(false);
1504         MappingRecordBuilder etlr = new MappingRecordBuilder();
1505         etlr.setRecordTtl(254);
1506         etlr.setAction(Action.NoAction);
1507         etlr.setAuthoritative(false);
1508         etlr.setMapVersion((short) 0);
1509         etlr.setEid(registerEID);
1510         etlr.setRecordTtl(254);
1511         LocatorRecordBuilder record = new LocatorRecordBuilder();
1512         record.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
1513         record.setLocalLocator(false);
1514         record.setRlocProbed(false);
1515         record.setRouted(true);
1516         record.setMulticastPriority((short) 0);
1517         record.setMulticastWeight((short) 0);
1518         record.setPriority((short) 0);
1519         record.setWeight((short) 0);
1520         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1521         etlr.getLocatorRecord().add(record.build());
1522         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1523         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1524         sendMapRegister(mapRegister.build());
1525         MapNotify mapNotify = receiveMapNotify();
1526         assertEquals(8, mapNotify.getNonce().longValue());
1527         sleepForSeconds(1);
1528         MapRequestBuilder mapRequest = new MapRequestBuilder();
1529         mapRequest.setNonce((long) 4);
1530         mapRequest.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1531         mapRequest.setEidItem(new ArrayList<EidItem>());
1532         mapRequest.setAuthoritative(false);
1533         mapRequest.setMapDataPresent(false);
1534         mapRequest.setPitr(false);
1535         mapRequest.setProbe(false);
1536         mapRequest.setSmr(false);
1537         mapRequest.setSmrInvoked(false);
1538         mapRequest.getEidItem().add(new EidItemBuilder().setEid(matchedAddress).build());
1539         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
1540         mapRequest.getItrRloc().add(
1541                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1542         sendMapRequest(mapRequest.build());
1543         MapReply mapReply = receiveMapReply();
1544         assertEquals(4, mapReply.getNonce().longValue());
1545         assertEquals(record.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1546                 .get(0).getRloc());
1547         mapRequest.setEidItem(new ArrayList<EidItem>());
1548         mapRequest.getEidItem().add(new EidItemBuilder().setEid(unMatchedAddress).build());
1549         sendMapRequest(mapRequest.build());
1550         mapReply = receiveMapReply();
1551         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1552     }
1553 /*
1554     // This registers an IP with a MapRegister, then adds a password via the
1555     // northbound REST API
1556     // and checks that the password works
1557     public void testPasswordExactMatch() throws Exception {
1558         cleanUP();
1559         String ipString = "10.0.0.1";
1560         LispIpv4Address address = LispAddressUtil.asIPAfiAddress(ipString);
1561         int mask = 32;
1562         String pass = "pass";
1563
1564         URL url = createPutURL("key");
1565
1566         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
1567
1568         LOG.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
1569         LOG.trace("Address: " + address);
1570
1571         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232,
1572                 (byte) 31, (byte) 249, (byte) 87,
1573                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53,
1574                 (byte) 196, (byte) 62 };
1575
1576         byte[] zeros = new byte[20];
1577
1578         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1579
1580         // build a MapRegister
1581         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1582         mapRegister.setWantMapNotify(true);
1583         mapRegister.setNonce((long) 8);
1584         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1585         etlr.setLispAddressContainer(LispAddressUtil.toContainer(address));
1586         etlr.setMaskLength((short) mask);
1587         etlr.setRecordTtl(254);
1588         LocatorRecordBuilder record = new LocatorRecordBuilder();
1589         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1590         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1591         etlr.getLocatorRecord().add(record.build());
1592         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1593         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1594
1595         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1596         mapRegister.setAuthenticationData(zeros);
1597
1598         sendMapRegister(mapRegister.build());
1599         assertNoPacketReceived(3000);
1600
1601         mapRegister.setAuthenticationData(expectedSha);
1602
1603         sendMapRegister(mapRegister.build());
1604
1605         assertMapNotifyReceived();
1606     }
1607
1608     public void testPasswordMaskMatch() throws Exception {
1609         cleanUP();
1610         LispIpv4Address addressInRange = LispAddressUtil.asIPAfiAddress("10.20.30.40");
1611         LispIpv4Address addressOutOfRange = LispAddressUtil.asIPAfiAddress("20.40.30.40");
1612         LispIpv4Address range = LispAddressUtil.asIPAfiAddress("10.20.30.0");
1613
1614         int mask = 32;
1615         String pass = "pass";
1616
1617         URL url = createPutURL("key");
1618         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
1619
1620         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
1621         // build a MapRegister
1622         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1623
1624         mapRegister.setWantMapNotify(true);
1625         mapRegister.setNonce((long) 8);
1626         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1627         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressInRange));
1628         etlr.setMaskLength((short) mask);
1629         etlr.setRecordTtl(254);
1630         LocatorRecordBuilder record = new LocatorRecordBuilder();
1631         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1632         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
1633         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
1634         etlr.getLocatorRecord().add(record.build());
1635         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1636         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
1637
1638         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
1639         mapRegister
1640                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4,
1641                 -67, -113, 104, -110, -71 });
1642
1643         sendMapRegister(mapRegister.build());
1644
1645         assertMapNotifyReceived();
1646
1647         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressOutOfRange));
1648         mapRegister
1649                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123,
1650                 -71, -14, -99, 67, -23, -73 });
1651
1652         sendMapRegister(mapRegister.build());
1653         assertNoPacketReceived(3000);
1654     }
1655 */
1656     // takes an address, packs it in a MapRegister and sends it
1657     private void registerAddress(Eid eid) throws SocketTimeoutException {
1658         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1659         sleepForSeconds(1);
1660         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1661         mapRegisterBuilder.setWantMapNotify(true);
1662         mapRegisterBuilder.setKeyId((short) 0);
1663         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1664         mapRegisterBuilder.setNonce((long) 8);
1665         mapRegisterBuilder.setProxyMapReply(false);
1666         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1667         etlrBuilder.setEid(eid);
1668         etlrBuilder.setRecordTtl(254);
1669         etlrBuilder.setAction(Action.NoAction);
1670         etlrBuilder.setAuthoritative(false);
1671         etlrBuilder.setMapVersion((short) 0);
1672         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1673         recordBuilder.setLocalLocator(false);
1674         recordBuilder.setRlocProbed(false);
1675         recordBuilder.setRouted(true);
1676         recordBuilder.setMulticastPriority((short) 0);
1677         recordBuilder.setMulticastWeight((short) 0);
1678         recordBuilder.setPriority((short) 0);
1679         recordBuilder.setWeight((short) 0);
1680         recordBuilder.setRloc(locatorEid);
1681         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1682         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1683         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1684         mapRegisterBuilder.getMappingRecordItem().add(
1685                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
1686         sendMapRegister(mapRegisterBuilder.build());
1687         MapNotify mapNotify = receiveMapNotify();
1688         assertEquals(8, mapNotify.getNonce().longValue());
1689     }
1690
1691     private MapReply queryForAddress(Eid eid, String srcEid) throws SocketTimeoutException {
1692         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1693         mapRequestBuilder.setNonce((long) 4);
1694         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1695         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1696         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1697         if (srcEid != null) {
1698             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(srcEid)).build());
1699         } else {
1700             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress))
1701                     .build());
1702         }
1703         mapRequestBuilder.getItrRloc().add(
1704                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1705         mapRequestBuilder.setAuthoritative(false);
1706         mapRequestBuilder.setMapDataPresent(false);
1707         mapRequestBuilder.setPitr(false);
1708         mapRequestBuilder.setProbe(false);
1709         mapRequestBuilder.setSmr(false);
1710         mapRequestBuilder.setSmrInvoked(false);
1711         sendMapRequest(mapRequestBuilder.build());
1712         return receiveMapReply();
1713     }
1714
1715     // takes an address, packs it in a MapRegister, sends it, returns the
1716     // MapReply
1717     private MapReply registerAddressAndQuery(Eid eid) throws SocketTimeoutException {
1718         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1719         sleepForSeconds(1);
1720         MapRegisterBuilder mapRegisterBuilder = new MapRegisterBuilder();
1721         mapRegisterBuilder.setWantMapNotify(true);
1722         mapRegisterBuilder.setKeyId((short) 0);
1723         mapRegisterBuilder.setAuthenticationData(new byte[0]);
1724         mapRegisterBuilder.setNonce((long) 8);
1725         mapRegisterBuilder.setProxyMapReply(false);
1726         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
1727         etlrBuilder.setEid(eid);
1728         etlrBuilder.setRecordTtl(254);
1729         etlrBuilder.setAction(Action.NoAction);
1730         etlrBuilder.setAuthoritative(false);
1731         etlrBuilder.setMapVersion((short) 0);
1732         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
1733         recordBuilder.setLocalLocator(false);
1734         recordBuilder.setRlocProbed(false);
1735         recordBuilder.setRouted(true);
1736         recordBuilder.setMulticastPriority((short) 0);
1737         recordBuilder.setMulticastWeight((short) 0);
1738         recordBuilder.setPriority((short) 0);
1739         recordBuilder.setWeight((short) 0);
1740         recordBuilder.setRloc(locatorEid);
1741         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
1742         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
1743         mapRegisterBuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
1744         mapRegisterBuilder.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(
1745                 etlrBuilder.build()).build());
1746         sendMapRegister(mapRegisterBuilder.build());
1747         MapNotify mapNotify = receiveMapNotify();
1748         assertEquals(8, mapNotify.getNonce().longValue());
1749         // wait for the notifications to propagate
1750         sleepForSeconds(1);
1751         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1752         mapRequestBuilder.setNonce((long) 4);
1753         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1754         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
1755         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
1756         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
1757         mapRequestBuilder.getItrRloc().add(
1758                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
1759         mapRequestBuilder.setAuthoritative(false);
1760         mapRequestBuilder.setMapDataPresent(false);
1761         mapRequestBuilder.setPitr(false);
1762         mapRequestBuilder.setProbe(false);
1763         mapRequestBuilder.setSmr(false);
1764         mapRequestBuilder.setSmrInvoked(false);
1765         sendMapRequest(mapRequestBuilder.build());
1766         return receiveMapReply();
1767     }
1768
1769     // ------------------------------- LCAF Tests ---------------------------
1770
1771     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
1772         cleanUP();
1773         String ipPrefix = "10.20.30.200/32";
1774         String macString = "01:02:03:04:05:06";
1775
1776         SourceDestKeyBuilder builder = new SourceDestKeyBuilder();
1777         builder.setSource(new SimpleAddress(new IpPrefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
1778                 .ietf.inet.types.rev130715.Ipv4Prefix(ipPrefix))));
1779         builder.setDest(new SimpleAddress(new MacAddress(macString)));
1780
1781         EidBuilder eb = new EidBuilder();
1782         eb.setAddressType(SourceDestKeyLcaf.class);
1783         eb.setVirtualNetworkId(null);
1784         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1785                 .lisp.address.address.SourceDestKeyBuilder().setSourceDestKey(builder.build()).build());
1786
1787         MapReply reply = registerAddressAndQuery(eb.build());
1788
1789         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1790         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1791         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1792
1793         SimpleAddress receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource();
1794         SimpleAddress receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest();
1795
1796         assertNotNull(receivedAddr1.getIpPrefix().getIpv4Prefix());
1797         assertNotNull(receivedAddr2.getMacAddress());
1798
1799         IpPrefix receivedIP = receivedAddr1.getIpPrefix();
1800         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1801
1802         assertEquals(ipPrefix, receivedIP.getIpv4Prefix().getValue());
1803         assertEquals(macString, receivedMAC.getValue());
1804     }
1805
1806     public void registerAndQuery__SrcDestLCAFOverlap() throws SocketTimeoutException {
1807         cleanUP();
1808         String ipString1 = "10.10.10.0";
1809         String ipString2 = "20.20.20.0";
1810         String ipPrefix1 = ipString1 + "/24";
1811         String ipPrefix2 = ipString2 + "/24";
1812
1813         Eid srcDst = LispAddressUtil.asSrcDstEid(ipString1, ipString2, 24, 24, 0);
1814         registerAddress(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2));
1815         registerAddress(srcDst);
1816
1817         // exact match
1818         MapReply reply = queryForAddress(srcDst, null);
1819
1820         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1821         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
1822         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
1823
1824         IpPrefix receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource().getIpPrefix();
1825         IpPrefix receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest().getIpPrefix();
1826
1827         assertNotNull(receivedAddr1.getIpv4Prefix());
1828         assertNotNull(receivedAddr2.getIpv4Prefix());
1829
1830         assertEquals(ipPrefix1, receivedAddr1.getIpv4Prefix().getValue());
1831         assertEquals(ipPrefix2, receivedAddr2.getIpv4Prefix().getValue());
1832
1833         // srcEid/dstEid match
1834         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "10.10.10.1");
1835         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1836         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
1837
1838         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
1839
1840         // dstEid match only
1841         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "1.2.3.4");
1842         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1843         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
1844
1845         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
1846     }
1847
1848     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
1849         cleanUP();
1850         String ipString = "10.20.30.200";
1851         String macString = "01:02:03:04:05:06";
1852         SimpleAddress addrToSend1 = new SimpleAddress(new IpAddress(new Ipv4Address(ipString)));
1853         SimpleAddress addrToSend2 = new SimpleAddress(new MacAddress(macString));
1854         Eid kv = LispAddressUtil.asKeyValueAddressEid(addrToSend1, addrToSend2);
1855
1856         MapReply reply = registerAddressAndQuery(kv);
1857
1858         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1859         assertEquals(KeyValueAddressLcaf.class, fromNetwork.getAddressType());
1860         KeyValueAddress keyValueFromNetwork = (KeyValueAddress) fromNetwork.getAddress();
1861
1862         SimpleAddress receivedAddr1 = keyValueFromNetwork.getKeyValueAddress().getKey();
1863         SimpleAddress receivedAddr2 = keyValueFromNetwork.getKeyValueAddress().getValue();
1864
1865         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1866         assertNotNull(receivedAddr2.getMacAddress());
1867
1868         Ipv4Address receivedIP = receivedAddr1.getIpAddress().getIpv4Address();
1869         MacAddress receivedMAC = receivedAddr2.getMacAddress();
1870
1871         assertEquals(ipString, receivedIP.getValue());
1872         assertEquals(macString, receivedMAC.getValue());
1873     }
1874
1875     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
1876         cleanUP();
1877         String macString = "01:02:03:04:05:06";
1878         String ipString = "10.20.255.30";
1879         List<SimpleAddress> addresses = new ArrayList<SimpleAddress>();
1880         addresses.add(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1881         addresses.add(new SimpleAddress(new MacAddress(macString)));
1882         AfiListBuilder listbuilder = new AfiListBuilder();
1883         listbuilder.setAddressList(addresses);
1884
1885         EidBuilder eb = new EidBuilder();
1886         eb.setAddressType(AfiListLcaf.class);
1887         eb.setVirtualNetworkId(null);
1888         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1889                 .lisp.address.address.AfiListBuilder().setAfiList(listbuilder.build()).build());
1890
1891         MapReply reply = registerAddressAndQuery(eb.build());
1892
1893         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1894
1895         assertEquals(AfiListLcaf.class, receivedAddress.getAddressType());
1896
1897         AfiList listAddrFromNetwork = (AfiList) receivedAddress.getAddress();
1898         SimpleAddress receivedAddr1 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(0);
1899         SimpleAddress receivedAddr2 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(1);
1900
1901         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
1902         assertNotNull(receivedAddr2.getMacAddress());
1903
1904         assertEquals(macString, receivedAddr2.getMacAddress().getValue());
1905         assertEquals(ipString, receivedAddr1.getIpAddress().getIpv4Address().getValue());
1906     }
1907
1908     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
1909         cleanUP();
1910         String ipString = "10.20.255.30";
1911         int instanceId = 6;
1912
1913         EidBuilder eb = new EidBuilder();
1914         eb.setAddressType(Ipv4PrefixAfi.class);
1915         eb.setVirtualNetworkId(new InstanceIdType((long) instanceId));
1916         eb.setAddress(new Ipv4PrefixBuilder().setIpv4Prefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
1917                 .yang.ietf.inet.types.rev130715.Ipv4Prefix(ipString)).build());
1918
1919         MapReply reply = registerAddressAndQuery(eb.build());
1920
1921         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1922         assertEquals(Ipv4PrefixAfi.class, receivedAddress.getAddressType());
1923
1924         assertEquals(ipString, ((Ipv4Prefix) receivedAddress.getAddress()).getIpv4Prefix().getValue());
1925
1926         assertEquals(instanceId, receivedAddress.getVirtualNetworkId().getValue().intValue());
1927     }
1928
1929     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
1930         cleanUP();
1931         String macString = "01:02:03:04:05:06";
1932         String ipString = "10.20.255.30";
1933         HopBuilder hopBuilder = new HopBuilder();
1934         hopBuilder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1935         hopBuilder.setLrsBits(new LrsBits(true, false, true));
1936         Hop hop1 = hopBuilder.build();
1937         hopBuilder.setAddress(new SimpleAddress(new MacAddress(macString)));
1938         hopBuilder.setLrsBits(new LrsBits(false, true, false));
1939         Hop hop2 = hopBuilder.build();
1940         ExplicitLocatorPathBuilder elpBuilder = new ExplicitLocatorPathBuilder();
1941         elpBuilder.setHop(new ArrayList<Hop>());
1942         elpBuilder.getHop().add(hop1);
1943         elpBuilder.getHop().add(hop2);
1944
1945         EidBuilder eb = new EidBuilder();
1946         eb.setAddressType(ExplicitLocatorPathLcaf.class);
1947         eb.setVirtualNetworkId(null);
1948         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
1949                 .lisp.address.address.ExplicitLocatorPathBuilder().setExplicitLocatorPath(elpBuilder.build()).build());
1950
1951         MapReply reply = registerAddressAndQuery(eb.build());
1952
1953         assertEquals(ExplicitLocatorPathLcaf.class, reply.getMappingRecordItem().get(0).getMappingRecord().getEid()
1954                 .getAddressType());
1955
1956         ExplicitLocatorPath receivedAddress = (ExplicitLocatorPath) reply.getMappingRecordItem().get(0)
1957                 .getMappingRecord().getEid().getAddress();
1958
1959         Hop receivedHop1 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(0);
1960         Hop receivedHop2 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(1);
1961
1962         assertEquals(true, receivedHop1.getLrsBits().isLookup());
1963         assertEquals(false, receivedHop1.getLrsBits().isRlocProbe());
1964         assertEquals(true, receivedHop1.getLrsBits().isStrict());
1965
1966         assertEquals(false, receivedHop2.getLrsBits().isLookup());
1967         assertEquals(true, receivedHop2.getLrsBits().isRlocProbe());
1968         assertEquals(false, receivedHop2.getLrsBits().isStrict());
1969
1970         assertNotNull(receivedHop1.getAddress().getIpAddress().getIpv4Address());
1971         assertNotNull(receivedHop2.getAddress().getMacAddress());
1972
1973         assertEquals(ipString, receivedHop1.getAddress().getIpAddress().getIpv4Address().getValue());
1974         assertEquals(macString, receivedHop2.getAddress().getMacAddress().getValue());
1975     }
1976
1977     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
1978         cleanUP();
1979         String ipString = "1.2.3.4";
1980         short protocol = 1;
1981         int ipTOs = 2;
1982         int localPortLow = 3;
1983         int localPortHigh = 4;
1984         int remotePortLow = 4;
1985         int remotePortHigh = 5;
1986
1987         ApplicationDataBuilder builder = new ApplicationDataBuilder();
1988         builder.setIpTos(ipTOs);
1989         builder.setProtocol(protocol);
1990         builder.setLocalPortLow(new PortNumber(localPortLow));
1991         builder.setLocalPortHigh(new PortNumber(localPortHigh));
1992         builder.setRemotePortLow(new PortNumber(remotePortLow));
1993         builder.setRemotePortHigh(new PortNumber(remotePortHigh));
1994         builder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
1995
1996         EidBuilder eb = new EidBuilder();
1997         eb.setAddressType(ApplicationDataLcaf.class);
1998         eb.setVirtualNetworkId(null);
1999         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2000                 .lisp.address.address.ApplicationDataBuilder().setApplicationData(builder.build()).build());
2001         Eid addressToSend = eb.build();
2002
2003         MapReply reply = registerAddressAndQuery(addressToSend);
2004
2005         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2006
2007         assertEquals(ApplicationDataLcaf.class, receivedAddress.getAddressType());
2008
2009         ApplicationData receivedApplicationDataAddress = (ApplicationData) receivedAddress.getAddress();
2010         assertEquals(protocol, receivedApplicationDataAddress.getApplicationData().getProtocol().intValue());
2011         assertEquals(ipTOs, receivedApplicationDataAddress.getApplicationData().getIpTos().intValue());
2012         assertEquals(localPortLow, receivedApplicationDataAddress.getApplicationData().getLocalPortLow().getValue()
2013                 .intValue());
2014         assertEquals(localPortHigh, receivedApplicationDataAddress.getApplicationData().getLocalPortHigh().getValue()
2015                 .intValue());
2016         assertEquals(remotePortLow, receivedApplicationDataAddress.getApplicationData().getRemotePortLow().getValue()
2017                 .intValue());
2018         assertEquals(remotePortHigh, receivedApplicationDataAddress.getApplicationData().getRemotePortHigh().getValue()
2019                 .intValue());
2020
2021         SimpleAddress ipAddressReceived = receivedApplicationDataAddress.getApplicationData().getAddress();
2022         assertEquals(ipString, ipAddressReceived.getIpAddress().getIpv4Address().getValue());
2023     }
2024
2025     // ------------------- TimeOut Tests -----------
2026
2027     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
2028         cleanUP();
2029         ConfigIni.getInstance().setSmrRetryCount(0);
2030         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2031         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2032         sleepForSeconds(1);
2033         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2034         mapRequestBuilder.setNonce((long) 4);
2035         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
2036         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2037         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
2038         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2039         mapRequestBuilder.getItrRloc().add(
2040                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2041
2042         sendMapRequest(mapRequestBuilder.build());
2043         MapReply mapReply = receiveMapReply();
2044         assertEquals(4, mapReply.getNonce().longValue());
2045         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
2046
2047         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
2048         mapRegisterbuilder.setWantMapNotify(true);
2049         mapRegisterbuilder.setNonce((long) 8);
2050
2051         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
2052         etlrBuilder.setEid(eid);
2053         etlrBuilder.setRecordTtl(254);
2054
2055         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
2056         recordBuilder.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2057         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
2058         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
2059         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2060         mapRegisterbuilder.getMappingRecordItem().add(
2061                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
2062
2063         sendMapRegister(mapRegisterbuilder.build());
2064         MapNotify mapNotify = receiveMapNotify();
2065         assertEquals(8, mapNotify.getNonce().longValue());
2066         sleepForSeconds(1);
2067
2068         sendMapRequest(mapRequestBuilder.build());
2069         mapReply = receiveMapReply();
2070         assertEquals(4, mapReply.getNonce().longValue());
2071         assertEquals(recordBuilder.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2072                 .getLocatorRecord().get(0).getRloc());
2073
2074         causeEntryToBeCleaned();
2075         sendMapRequest(mapRequestBuilder.build());
2076         mapReply = receiveMapReply();
2077         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
2078     }
2079
2080     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
2081         cleanUP();
2082         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2083         MapRequest mapRequest = createMapRequest(eid);
2084
2085         testTTLBeforeRegister(mapRequest);
2086
2087         registerForTTL(eid);
2088
2089         testTTLAfterRegister(mapRequest);
2090
2091         causeEntryToBeCleaned();
2092         testTTLAfterClean(mapRequest);
2093
2094         //northboundAddKey();
2095         //testTTLAfterAutherize(mapRequest);
2096
2097     }
2098
2099     private void timedOutMappingRecord() {
2100         cleanUP();
2101         mapService.setMappingMerge(true);
2102         // mapping expires after 1 second
2103         ConfigIni.getInstance().setRegistrationValiditySb(1000L);
2104
2105         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32", new InstanceIdType(10L));
2106         final XtrId xtrId = new XtrId(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
2107         final SiteId siteId = new SiteId(new byte[]{1, 2, 3, 4, 5, 6, 7, 8});
2108
2109         final LocatorRecord locatorRecord = new LocatorRecordBuilder()
2110                 .setRloc(LispAddressUtil.asIpv4Rloc("1.1.1.1")).setLocatorId("locator-id").build();
2111         final MappingRecord mappingRecord = new MappingRecordBuilder()
2112                 .setEid(eid)
2113                 .setSiteId(siteId)
2114                 .setRecordTtl(1000)
2115                 .setXtrId(xtrId)
2116                 .setAction(Action.NoAction)
2117                 .setAuthoritative(true)
2118                 .setLocatorRecord(Lists.newArrayList()).build();
2119         mappingRecord.getLocatorRecord().add(locatorRecord);
2120
2121         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2122         mapService.addMapping(MappingOrigin.Southbound, eid, siteId,
2123                 new MappingData(mappingRecord, System.currentTimeMillis()));
2124         sleepForSeconds(2);
2125
2126         MappingRecord resultRecord = (MappingRecord) mapService.getMapping(MappingOrigin.Southbound, eid);
2127         assertNull(resultRecord);
2128     }
2129
2130     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
2131         MapReply mapReply;
2132         sendMapRequest(mapRequest);
2133         mapReply = receiveMapReply();
2134         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2135     }
2136
2137     private void causeEntryToBeCleaned() {
2138         // TODO XXX for the time being, to keep master and stable/lithium in sync, we need to remove the forceful
2139         // expiration of DAO entries. Once we're past this, we'll have to expose methods to setTimeUnit(TimeUnit)
2140         // and cleanOld() (expired) entries in IFlowMapping (and perhaps ILispDAO) and use them here.
2141         mapService.cleanCachedMappings();
2142     }
2143
2144     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
2145         MapReply mapReply;
2146         sendMapRequest(mapRequest);
2147         mapReply = receiveMapReply();
2148         assertEquals(LispAddressUtil.asIpv4Rloc("4.3.2.1"), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2149                 .getLocatorRecord().get(0).getRloc());
2150         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
2151     }
2152
2153     private void registerForTTL(Eid eid) throws SocketTimeoutException {
2154         MapRegister mapRegister = createMapRegister(eid);
2155         sendMapRegister(mapRegister);
2156         assertMapNotifyReceived();
2157     }
2158
2159     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
2160         MapReply mapReply;
2161         sendMapRequest(mapRequest);
2162         mapReply = receiveMapReply();
2163         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2164     }
2165 /*
2166     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
2167         MapReply mapReply;
2168         sendMapRequest(mapRequest);
2169         mapReply = receiveMapReply();
2170         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
2171     }
2172 */
2173     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
2174         assertEquals(expectedTTL, mapReply.getMappingRecordItem().get(0).getMappingRecord().getRecordTtl().intValue());
2175         assertEquals(expectedAction, mapReply.getMappingRecordItem().get(0).getMappingRecord().getAction());
2176     }
2177
2178     private MapRegister createMapRegister(Eid eid, Rloc rloc) {
2179         MapRegisterBuilder mapRegisterbuilder = new MapRegisterBuilder();
2180         mapRegisterbuilder.setWantMapNotify(true);
2181         mapRegisterbuilder.setNonce((long) 8);
2182         mapRegisterbuilder.setKeyId((short) 0);
2183         MappingRecordBuilder etlrBuilder = new MappingRecordBuilder();
2184         etlrBuilder.setEid(eid);
2185         etlrBuilder.setRecordTtl(254);
2186         etlrBuilder.setAuthoritative(false);
2187         etlrBuilder.setAction(Action.NoAction);
2188         LocatorRecordBuilder recordBuilder = new LocatorRecordBuilder();
2189         recordBuilder.setRloc(rloc);
2190         etlrBuilder.setLocatorRecord(new ArrayList<LocatorRecord>());
2191         etlrBuilder.getLocatorRecord().add(recordBuilder.build());
2192         mapRegisterbuilder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2193         mapRegisterbuilder.getMappingRecordItem().add(
2194                 new MappingRecordItemBuilder().setMappingRecord(etlrBuilder.build()).build());
2195         MapRegister mapRegister = mapRegisterbuilder.build();
2196         return mapRegister;
2197     }
2198
2199     private MapRegister createMapRegister(Eid eid) {
2200         return createMapRegister(eid, LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2201     }
2202
2203     private MapRequest createMapRequest(Eid eid) {
2204         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2205         mapRequestBuilder.setNonce((long) 4);
2206         mapRequestBuilder.setPitr(false);
2207         mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.getNoAddressEid()).build());
2208         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2209         mapRequestBuilder.getEidItem().add(new EidItemBuilder().setEid(eid).build());
2210         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2211         mapRequestBuilder.getItrRloc().add(
2212                 new ItrRlocBuilder().setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2213         MapRequest mr = mapRequestBuilder.build();
2214         return mr;
2215     }
2216
2217     public void testSimpleNonProxy() throws SocketTimeoutException, SocketException {
2218         cleanUP();
2219         String rloc = "127.0.0.3";
2220         int port = LispMessage.PORT_NUM;
2221         Rloc ipRloc = LispAddressUtil.asIpv4Rloc(rloc);
2222         sendProxyMapRequest(rloc, port, ipRloc);
2223
2224     }
2225
2226     public void testNonProxyOtherPort() throws SocketTimeoutException, SocketException {
2227         cleanUP();
2228         String rloc = "127.0.0.3";
2229         int port = 4350;
2230
2231         RlocBuilder rb = new RlocBuilder();
2232         rb.setAddressType(ApplicationDataLcaf.class);
2233         rb.setVirtualNetworkId(null);
2234         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2235                 .lisp.address.address.ApplicationDataBuilder()
2236                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2237                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2238         Rloc adLcaf = rb.build();
2239
2240         LOG.info("testNonProxyOtherPort:" + LispAddressStringifier.getString(adLcaf));
2241         sendProxyMapRequest(rloc, port, adLcaf);
2242
2243     }
2244
2245     private class XtrRequestMappingListener implements OdlLispProtoListener {
2246
2247         @Override
2248         public void onGotMapReply(GotMapReply notification) {
2249         }
2250
2251         @Override
2252         public void onAddMapping(AddMapping notification) {
2253         }
2254
2255         @Override
2256         public void onXtrReplyMapping(XtrReplyMapping notification) {
2257         }
2258
2259         @Override
2260         public void onRequestMapping(RequestMapping notification) {
2261         }
2262
2263         @Override
2264         public void onGotMapNotify(GotMapNotify notification) {
2265         }
2266
2267         @Override
2268         public void onXtrRequestMapping(XtrRequestMapping notification) {
2269         }
2270
2271         @Override
2272         public void onMappingKeepAlive(MappingKeepAlive notification) {
2273         }
2274
2275     }
2276
2277     public void testRecievingNonProxyOnXtrPort() throws SocketTimeoutException, SocketException, Throwable {
2278         cleanUP();
2279         configLispPlugin.shouldListenOnXtrPort(true);
2280         notificationCalled = false;
2281         final String eid = "10.10.10.10/32";
2282         String rloc = "127.0.0.3";
2283         int port = LispMessage.XTR_PORT_NUM;
2284
2285         RlocBuilder rb = new RlocBuilder();
2286         rb.setAddressType(ApplicationDataLcaf.class);
2287         rb.setVirtualNetworkId(null);
2288         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2289                 .lisp.address.address.ApplicationDataBuilder()
2290                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2291                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2292         Rloc adLcaf = rb.build();
2293
2294         final MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2295         ((LispMappingService) lms).getNotificationService().registerNotificationListener(
2296                 new XtrRequestMappingListener() {
2297
2298             @Override
2299             public void onXtrRequestMapping(XtrRequestMapping notification) {
2300                 assertEquals(((Ipv4Prefix) mapRequest.getEidItem().get(0).getEid().getAddress())
2301                         .getIpv4Prefix().getValue(), eid);
2302                 notificationCalled = true;
2303                 LOG.warn("notification arrived");
2304             }
2305         });
2306         sendMapRequest(mapRequest, port);
2307         for (int i = 0; i < MAX_NOTIFICATION_RETRYS; i++) {
2308             if (notificationCalled) {
2309                 return;
2310             } else {
2311                 LOG.warn("notification hasn't arrived, sleeping...");
2312                 Thread.sleep(500);
2313             }
2314         }
2315
2316         fail("Notification hasn't arrived");
2317
2318     }
2319
2320     private void sendProxyMapRequest(String rloc, int port, Rloc adLcaf) throws SocketTimeoutException,
2321             SocketException {
2322         String eid = "10.1.0.1/32";
2323         MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2324         sendMapRequest(mapRequest);
2325         DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
2326         MapRequest receivedMapRequest = receiveMapRequest(nonProxySocket);
2327         assertEquals(mapRequest.getNonce(), receivedMapRequest.getNonce());
2328         assertEquals(mapRequest.getSourceEid(), receivedMapRequest.getSourceEid());
2329         assertEquals(mapRequest.getItrRloc(), receivedMapRequest.getItrRloc());
2330         assertEquals(mapRequest.getEidItem(), receivedMapRequest.getEidItem());
2331         nonProxySocket.close();
2332     }
2333
2334     private MapRequest createNonProxyMapRequest(String eid, Rloc adLcaf) throws SocketTimeoutException {
2335         MapRegister mr = createMapRegister(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2336         LocatorRecord record = new LocatorRecordBuilder(mr.getMappingRecordItem().get(0).getMappingRecord()
2337                 .getLocatorRecord().get(0)).setRloc(adLcaf).build();
2338         mr.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().set(0, record);
2339         sendMapRegister(mr);
2340         assertMapNotifyReceived();
2341         MapRequest mapRequest = createMapRequest(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2342         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
2343         builder.setPitr(true);
2344         mapRequest = builder.build();
2345         return mapRequest;
2346     }
2347
2348     private void assertMapNotifyReceived() throws SocketTimeoutException {
2349         receiveMapNotify();
2350     }
2351
2352     private MapReply receiveMapReply() throws SocketTimeoutException {
2353         return receiveMapReply(socket, 1000);
2354     }
2355
2356     private MapRequest receiveMapRequest(DatagramSocket datagramSocket) throws SocketTimeoutException {
2357         return MapRequestSerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket(
2358                 datagramSocket, 30000).getData()), null);
2359     }
2360
2361     private MapNotify receiveMapNotify() throws SocketTimeoutException {
2362         return MapNotifySerializer.getInstance().deserialize(ByteBuffer.wrap(receivePacket().getData()));
2363     }
2364
2365     private void sendMapRequest(MapRequest mapRequest) {
2366         sendMapRequest(mapRequest, LispMessage.PORT_NUM);
2367     }
2368
2369     private void sendMapRequest(MapRequest mapRequest, int port) {
2370         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array(), port);
2371     }
2372
2373     private void sendMapRegister(MapRegister mapRegister) {
2374         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
2375     }
2376
2377     private void sendPacket(byte[] bytesToSend) {
2378         sendPacket(bytesToSend, LispMessage.PORT_NUM);
2379     }
2380
2381     private void sendPacket(byte[] bytesToSend, int port) {
2382         try {
2383             DatagramPacket packet = new DatagramPacket(bytesToSend, bytesToSend.length);
2384             initPacketAddress(packet, port);
2385             LOG.trace("Sending packet to LispPlugin on socket, port {}", port);
2386             socket.send(packet);
2387         } catch (Throwable t) {
2388             fail();
2389         }
2390     }
2391
2392     private DatagramPacket receivePacket() throws SocketTimeoutException {
2393         return receivePacket(6000);
2394     }
2395
2396     private DatagramPacket receivePacket(int timeout) throws SocketTimeoutException {
2397         return receivePacket(socket, timeout);
2398     }
2399
2400     private DatagramPacket receivePacket(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
2401         try {
2402             byte[] buffer = new byte[4096];
2403             DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
2404             LOG.trace("Waiting for packet from socket...");
2405             receivedSocket.setSoTimeout(timeout);
2406             receivedSocket.receive(receivePacket);
2407             LOG.trace("Received packet from socket!");
2408             return receivePacket;
2409         } catch (SocketTimeoutException ste) {
2410             throw ste;
2411         } catch (Throwable t) {
2412             fail();
2413             return null;
2414         }
2415     }
2416
2417     private MapReply receiveMapReply(DatagramSocket receivedSocket, int timeout) throws SocketTimeoutException {
2418         DatagramPacket packet;
2419         try {
2420             while (true) {
2421                 packet = receivePacket(receivedSocket, timeout);
2422                 final ByteBuffer buff = ByteBuffer.wrap(packet.getData());
2423                 final int type = ByteUtil.getUnsignedByte(buff, LispMessage.Pos.TYPE) >> 4;
2424                 final Object lispType = MessageType.forValue(type);
2425
2426                 if (lispType == MessageType.MapReply) {
2427                     return MapReplySerializer.getInstance().deserialize(buff);
2428                 }
2429             }
2430         } catch (SocketTimeoutException ste) {
2431             throw ste;
2432         }
2433     }
2434
2435     private void sleepForSeconds(int seconds) {
2436         try {
2437             Thread.sleep(seconds*1000);
2438         } catch (InterruptedException e) {
2439             LOG.warn("Interrupted while sleeping", e);
2440         }
2441     }
2442
2443     private void sleepForMilliseconds(long milliseconds) {
2444         try {
2445             Thread.sleep(milliseconds);
2446         } catch (InterruptedException e) {
2447             LOG.warn("Interrupted while sleeping", e);
2448         }
2449     }
2450
2451     private void initPacketAddress(DatagramPacket packet, int port) throws UnknownHostException {
2452         packet.setAddress(InetAddress.getByName(lispBindAddress));
2453         packet.setPort(port);
2454     }
2455
2456     private DatagramSocket initSocket(DatagramSocket socket, int port) {
2457         for (int i=0; i < NUM_OF_ATTEMPTS_TO_CREATE_SOCKET; i++) {
2458             try {
2459                 return new DatagramSocket(new InetSocketAddress(ourAddress, port));
2460             } catch (SocketException e) {
2461                 LOG.error("Can't initialize socket for {}", ourAddress, e);
2462             }
2463         }
2464         fail();
2465         return null;
2466     }
2467
2468     private byte[] extractWSUdpByteArray(String wiresharkHex) {
2469         final int HEADER_LEN = 42;
2470         byte[] res = new byte[1000];
2471         String[] split = wiresharkHex.split(" ");
2472         int counter = 0;
2473         for (String cur : split) {
2474             cur = cur.trim();
2475             if (cur.length() == 2) {
2476                 ++counter;
2477                 if (counter > HEADER_LEN) {
2478                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
2479                 }
2480
2481             }
2482         }
2483         return Arrays.copyOf(res, counter - HEADER_LEN);
2484     }
2485
2486     private String stateToString(int state) {
2487         switch (state) {
2488         case Bundle.ACTIVE:
2489             return "ACTIVE";
2490         case Bundle.INSTALLED:
2491             return "INSTALLED";
2492         case Bundle.RESOLVED:
2493             return "RESOLVED";
2494         case Bundle.UNINSTALLED:
2495             return "UNINSTALLED";
2496         default:
2497             return "Not CONVERTED";
2498         }
2499     }
2500
2501     private void areWeReady() throws InvalidSyntaxException {
2502         sleepForSeconds(5);
2503
2504         assertNotNull(bc);
2505         boolean debugit = false;
2506         Bundle b[] = bc.getBundles();
2507         for (Bundle element : b) {
2508             int state = element.getState();
2509             LOG.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v"
2510                     + element.getVersion() + ", state:" + stateToString(state));
2511             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
2512                 LOG.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
2513
2514                 // try {
2515                 // String host = element.getHeaders().get("FRAGMENT-HOST");
2516                 // if (host != null) {
2517                 // LOG.warn("Bundle " + element.getSymbolicName() +
2518                 // " is a fragment which is part of: " + host);
2519                 // LOG.warn("Required imports are: " +
2520                 // element.getHeaders().get("IMPORT-PACKAGE"));
2521                 // } else {
2522                 // element.start();
2523                 // }
2524                 // } catch (BundleException e) {
2525                 // LOG.error("BundleException:", e);
2526                 // fail();
2527                 // }
2528
2529                 debugit = true;
2530
2531             }
2532         }
2533         if (debugit) {
2534             LOG.warn(("Do some debugging because some bundle is unresolved"));
2535         }
2536         // assertNotNull(broker);
2537
2538         configLispPlugin.setLispAddress(lispBindAddress);
2539
2540         // Uncomment this code to Know which services were actually loaded to
2541         // BundleContext
2542
2543         /*
2544         for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
2545             LOG.info(sr.getBundle().getSymbolicName());
2546             LOG.info(sr.toString());
2547         }
2548         */
2549
2550         sleepForSeconds(1);
2551     }
2552
2553     private void cleanUP() {
2554         after();
2555         mapService.cleanCachedMappings();
2556         configLispPlugin.shouldListenOnXtrPort(false);
2557         socket = initSocket(socket, LispMessage.PORT_NUM);
2558
2559     }
2560
2561     private void restartSocket() {
2562         after();
2563         socket = initSocket(socket, LispMessage.PORT_NUM);
2564     }
2565
2566 }