3e806a736dddbdcd11175d8daca57c1bd903dc45
[onosfw.git] /
1 /*
2  * Copyright 2014-2015 Open Networking Laboratory
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onosproject.net.proxyarp.impl;
17
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Sets;
20 import org.junit.Before;
21 import org.junit.Test;
22 import org.onlab.packet.ARP;
23 import org.onlab.packet.Ethernet;
24 import org.onlab.packet.ICMP6;
25 import org.onlab.packet.IPacket;
26 import org.onlab.packet.IPv6;
27 import org.onlab.packet.Ip4Address;
28 import org.onlab.packet.Ip4Prefix;
29 import org.onlab.packet.Ip6Address;
30 import org.onlab.packet.Ip6Prefix;
31 import org.onlab.packet.IpPrefix;
32 import org.onlab.packet.MacAddress;
33 import org.onlab.packet.VlanId;
34 import org.onlab.packet.ndp.NeighborAdvertisement;
35 import org.onlab.packet.ndp.NeighborDiscoveryOptions;
36 import org.onlab.packet.ndp.NeighborSolicitation;
37 import org.onosproject.incubator.net.intf.Interface;
38 import org.onosproject.incubator.net.intf.InterfaceService;
39 import org.onosproject.net.ConnectPoint;
40 import org.onosproject.net.DefaultHost;
41 import org.onosproject.net.Device;
42 import org.onosproject.net.DeviceId;
43 import org.onosproject.net.Host;
44 import org.onosproject.net.HostId;
45 import org.onosproject.net.HostLocation;
46 import org.onosproject.net.Link;
47 import org.onosproject.net.Port;
48 import org.onosproject.net.PortNumber;
49 import org.onosproject.net.device.DeviceListener;
50 import org.onosproject.net.device.DeviceService;
51 import org.onosproject.net.edgeservice.impl.EdgeManager;
52 import org.onosproject.net.flow.DefaultTrafficTreatment;
53 import org.onosproject.net.flow.TrafficTreatment;
54 import org.onosproject.net.flow.instructions.Instruction;
55 import org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
56 import org.onosproject.net.host.HostService;
57 import org.onosproject.net.host.InterfaceIpAddress;
58 import org.onosproject.net.link.LinkListener;
59 import org.onosproject.net.link.LinkService;
60 import org.onosproject.net.packet.DefaultOutboundPacket;
61 import org.onosproject.net.packet.OutboundPacket;
62 import org.onosproject.net.packet.PacketServiceAdapter;
63 import org.onosproject.net.provider.ProviderId;
64 import org.onosproject.net.proxyarp.ProxyArpStore;
65 import org.onosproject.net.proxyarp.ProxyArpStoreDelegate;
66
67 import java.nio.ByteBuffer;
68 import java.util.ArrayList;
69 import java.util.Collections;
70 import java.util.List;
71 import java.util.Set;
72
73 import static org.easymock.EasyMock.anyObject;
74 import static org.easymock.EasyMock.createMock;
75 import static org.easymock.EasyMock.expect;
76 import static org.easymock.EasyMock.replay;
77 import static org.hamcrest.Matchers.anyOf;
78 import static org.hamcrest.Matchers.is;
79 import static org.junit.Assert.assertArrayEquals;
80 import static org.junit.Assert.assertEquals;
81 import static org.junit.Assert.assertFalse;
82 import static org.junit.Assert.assertNotNull;
83 import static org.junit.Assert.assertThat;
84 import static org.junit.Assert.assertTrue;
85
86 /**
87  * Tests for the {@link ProxyArpManager} class.
88  */
89 public class ProxyArpManagerTest {
90
91     private static final int NUM_DEVICES = 6;
92     private static final int NUM_PORTS_PER_DEVICE = 3;
93     private static final int NUM_ADDRESS_PORTS = NUM_DEVICES / 2;
94     private static final int NUM_FLOOD_PORTS = 3;
95
96     private static final Ip4Address IP1 = Ip4Address.valueOf("192.168.1.1");
97     private static final Ip4Address IP2 = Ip4Address.valueOf("192.168.1.2");
98     private static final Ip6Address IP3 = Ip6Address.valueOf("1000::1");
99     private static final Ip6Address IP4 = Ip6Address.valueOf("1000::2");
100
101     private static final ProviderId PID = new ProviderId("of", "foo");
102
103     private static final VlanId VLAN1 = VlanId.vlanId((short) 1);
104     private static final VlanId VLAN2 = VlanId.vlanId((short) 2);
105     private static final MacAddress MAC1 = MacAddress.valueOf("00:00:11:00:00:01");
106     private static final MacAddress MAC2 = MacAddress.valueOf("00:00:22:00:00:02");
107     private static final MacAddress MAC3 = MacAddress.valueOf("00:00:33:00:00:03");
108     private static final MacAddress MAC4 = MacAddress.valueOf("00:00:44:00:00:04");
109     private static final MacAddress SOLICITED_MAC3 = MacAddress.valueOf("33:33:FF:00:00:01");
110     private static final HostId HID1 = HostId.hostId(MAC1, VLAN1);
111     private static final HostId HID2 = HostId.hostId(MAC2, VLAN1);
112     private static final HostId HID3 = HostId.hostId(MAC3, VLAN1);
113     private static final HostId HID4 = HostId.hostId(MAC4, VLAN1);
114     private static final HostId SOLICITED_HID3 = HostId.hostId(SOLICITED_MAC3, VLAN1);
115
116     private static final DeviceId DID1 = getDeviceId(1);
117     private static final DeviceId DID2 = getDeviceId(2);
118     private static final PortNumber P1 = PortNumber.portNumber(1);
119     private static final HostLocation LOC1 = new HostLocation(DID1, P1, 123L);
120     private static final HostLocation LOC2 = new HostLocation(DID2, P1, 123L);
121     private static final byte[] ZERO_MAC_ADDRESS = MacAddress.ZERO.toBytes();
122
123     //Return values used for various functions of the TestPacketService inner class.
124     private boolean isEdgePointReturn;
125     private List<ConnectPoint> getEdgePointsNoArg;
126
127
128     private ProxyArpManager proxyArp;
129
130     private TestPacketService packetService;
131     private DeviceService deviceService;
132     private LinkService linkService;
133     private HostService hostService;
134     private InterfaceService interfaceService;
135
136     @Before
137     public void setUp() throws Exception {
138         proxyArp = new ProxyArpManager();
139         packetService = new TestPacketService();
140         proxyArp.packetService = packetService;
141         proxyArp.store = new TestProxyArpStoreAdapter();
142
143         proxyArp.edgeService = new TestEdgePortService();
144
145         // Create a host service mock here. Must be replayed by tests once the
146         // expectations have been set up
147         hostService = createMock(HostService.class);
148         proxyArp.hostService = hostService;
149
150         interfaceService = createMock(InterfaceService.class);
151         proxyArp.interfaceService = interfaceService;
152
153         createTopology();
154         proxyArp.deviceService = deviceService;
155         proxyArp.linkService = linkService;
156
157         proxyArp.activate();
158     }
159
160     /**
161      * Creates a fake topology to feed into the ARP module.
162      * <p>
163      * The default topology is a unidirectional ring topology. Each switch has
164      * 3 ports. Ports 2 and 3 have the links to neighbor switches, and port 1
165      * is free (edge port).
166      * The first half of the switches have IP addresses configured on their
167      * free ports (port 1). The second half of the switches have no IP
168      * addresses configured.
169      */
170     private void createTopology() {
171         deviceService = createMock(DeviceService.class);
172         linkService = createMock(LinkService.class);
173
174         deviceService.addListener(anyObject(DeviceListener.class));
175         linkService.addListener(anyObject(LinkListener.class));
176
177         createDevices(NUM_DEVICES, NUM_PORTS_PER_DEVICE);
178         createLinks(NUM_DEVICES);
179         addAddressBindings();
180     }
181
182     /**
183      * Creates the devices for the fake topology.
184      */
185     private void createDevices(int numDevices, int numPorts) {
186         List<Device> devices = new ArrayList<>();
187
188         for (int i = 1; i <= numDevices; i++) {
189             DeviceId devId = getDeviceId(i);
190             Device device = createMock(Device.class);
191             expect(device.id()).andReturn(devId).anyTimes();
192             replay(device);
193
194             devices.add(device);
195
196             List<Port> ports = new ArrayList<>();
197             for (int j = 1; j <= numPorts; j++) {
198                 Port port = createMock(Port.class);
199                 expect(port.number()).andReturn(PortNumber.portNumber(j)).anyTimes();
200                 replay(port);
201                 ports.add(port);
202             }
203
204             expect(deviceService.getPorts(devId)).andReturn(ports).anyTimes();
205             expect(deviceService.getDevice(devId)).andReturn(device).anyTimes();
206         }
207
208         expect(deviceService.getDevices()).andReturn(devices).anyTimes();
209         replay(deviceService);
210     }
211
212     /**
213      * Creates the links for the fake topology.
214      * NB: Only unidirectional links are created, as for this purpose all we
215      * need is to occupy the ports with some link.
216      */
217     private void createLinks(int numDevices) {
218         List<Link> links = new ArrayList<>();
219
220         for (int i = 1; i <= numDevices; i++) {
221             ConnectPoint src = new ConnectPoint(
222                     getDeviceId(i),
223                     PortNumber.portNumber(2));
224             ConnectPoint dst = new ConnectPoint(
225                     getDeviceId((i + 1 > numDevices) ? 1 : i + 1),
226                     PortNumber.portNumber(3));
227
228             Link link = createMock(Link.class);
229             expect(link.src()).andReturn(src).anyTimes();
230             expect(link.dst()).andReturn(dst).anyTimes();
231             replay(link);
232
233             links.add(link);
234         }
235
236         expect(linkService.getLinks()).andReturn(links).anyTimes();
237         replay(linkService);
238     }
239
240     private void addAddressBindings() {
241         Set<Interface> interfaces = Sets.newHashSet();
242
243         for (int i = 1; i <= NUM_ADDRESS_PORTS; i++) {
244             ConnectPoint cp = new ConnectPoint(getDeviceId(i), P1);
245
246             // Interface address for IPv4
247             Ip4Prefix prefix1 = Ip4Prefix.valueOf("10.0." + (2 * i - 1) + ".0/24");
248             Ip4Address addr1 = Ip4Address.valueOf("10.0." + (2 * i - 1) + ".1");
249             Ip4Prefix prefix2 = Ip4Prefix.valueOf("10.0." + (2 * i) + ".0/24");
250             Ip4Address addr2 = Ip4Address.valueOf("10.0." + (2 * i) + ".1");
251             InterfaceIpAddress ia1 = new InterfaceIpAddress(addr1, prefix1);
252             InterfaceIpAddress ia2 = new InterfaceIpAddress(addr2, prefix2);
253
254             // Interface address for IPv6
255             Ip6Prefix prefix3 = Ip6Prefix.valueOf((2 * i - 1) + "000::0/64");
256             Ip6Address addr3 = Ip6Address.valueOf((2 * i - 1) + "000::1");
257             Ip6Prefix prefix4 = Ip6Prefix.valueOf((2 * i) + "000::0/64");
258             Ip6Address addr4 = Ip6Address.valueOf((2 * i) + "000::1");
259             InterfaceIpAddress ia3 = new InterfaceIpAddress(addr3, prefix3);
260             InterfaceIpAddress ia4 = new InterfaceIpAddress(addr4, prefix4);
261
262             Interface intf1 = new Interface(cp, Sets.newHashSet(ia1, ia3),
263                     MacAddress.valueOf(2 * i - 1),
264                     VlanId.vlanId((short) 1));
265             Interface intf2 = new Interface(cp, Sets.newHashSet(ia2, ia4),
266                     MacAddress.valueOf(2 * i),
267                     VlanId.NONE);
268             interfaces.add(intf1);
269             interfaces.add(intf2);
270
271             expect(interfaceService.getInterfacesByPort(cp))
272                     .andReturn(Sets.newHashSet(intf1, intf2)).anyTimes();
273         }
274
275         expect(interfaceService.getInterfaces()).andReturn(interfaces).anyTimes();
276
277         for (int i = 1; i <= NUM_FLOOD_PORTS; i++) {
278             ConnectPoint cp = new ConnectPoint(getDeviceId(i + NUM_ADDRESS_PORTS),
279                     P1);
280
281             expect(interfaceService.getInterfacesByPort(cp))
282                     .andReturn(Collections.emptySet()).anyTimes();
283         }
284     }
285
286     /**
287      * Tests {@link ProxyArpManager#isKnown(org.onlab.packet.IpAddress)} in the
288      * case where the IP address is not known.
289      * Verifies the method returns false.
290      */
291     @Test
292     public void testNotKnown() {
293         expect(hostService.getHostsByIp(IP1)).andReturn(Collections.<Host>emptySet());
294         replay(hostService);
295         replay(interfaceService);
296
297         assertFalse(proxyArp.isKnown(IP1));
298     }
299
300     /**
301      * Tests {@link ProxyArpManager#isKnown(org.onlab.packet.IpAddress)} in the
302      * case where the IP address is known.
303      * Verifies the method returns true.
304      */
305     @Test
306     public void testKnown() {
307         Host host1 = createMock(Host.class);
308         Host host2 = createMock(Host.class);
309
310         expect(hostService.getHostsByIp(IP1))
311                 .andReturn(Sets.newHashSet(host1, host2));
312         replay(hostService);
313         replay(interfaceService);
314
315         assertTrue(proxyArp.isKnown(IP1));
316     }
317
318     /**
319      * Tests {@link ProxyArpManager#reply(Ethernet, ConnectPoint)} in the case where the
320      * destination host is known.
321      * Verifies the correct ARP reply is sent out the correct port.
322      */
323     @Test
324     public void testReplyKnown() {
325         //Set the return value of isEdgePoint from the edgemanager.
326         isEdgePointReturn = true;
327
328         Host replyer = new DefaultHost(PID, HID1, MAC1, VLAN1, getLocation(4),
329                 Collections.singleton(IP1));
330
331         Host requestor = new DefaultHost(PID, HID2, MAC2, VLAN1, getLocation(5),
332                 Collections.singleton(IP2));
333
334         expect(hostService.getHostsByIp(IP1))
335                 .andReturn(Collections.singleton(replyer));
336         expect(hostService.getHost(HID2)).andReturn(requestor);
337
338         replay(hostService);
339         replay(interfaceService);
340
341         Ethernet arpRequest = buildArp(ARP.OP_REQUEST, MAC2, null, IP2, IP1);
342
343         proxyArp.reply(arpRequest, getLocation(5));
344
345         assertEquals(1, packetService.packets.size());
346         Ethernet arpReply = buildArp(ARP.OP_REPLY, MAC1, MAC2, IP1, IP2);
347         verifyPacketOut(arpReply, getLocation(5), packetService.packets.get(0));
348     }
349
350     /**
351      * Tests {@link ProxyArpManager#reply(Ethernet, ConnectPoint)} in the case where the
352      * destination host is known.
353      * Verifies the correct NDP reply is sent out the correct port.
354      */
355     @Test
356     public void testReplyKnownIpv6() {
357         //Set the return value of isEdgePoint from the edgemanager.
358         isEdgePointReturn = true;
359
360         Host replyer = new DefaultHost(PID, HID3, MAC3, VLAN1, getLocation(4),
361                                        Collections.singleton(IP3));
362
363         Host requestor = new DefaultHost(PID, HID4, MAC4, VLAN1, getLocation(5),
364                                          Collections.singleton(IP4));
365
366         expect(hostService.getHostsByIp(IP3))
367                 .andReturn(Collections.singleton(replyer));
368         expect(hostService.getHost(HID4)).andReturn(requestor);
369
370         replay(hostService);
371         replay(interfaceService);
372
373         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
374                                        MAC4, SOLICITED_MAC3,
375                                        IP4, IP3);
376
377         proxyArp.reply(ndpRequest, getLocation(5));
378
379         assertEquals(1, packetService.packets.size());
380         Ethernet ndpReply = buildNDP(ICMP6.NEIGHBOR_ADVERTISEMENT,
381                                      MAC3, MAC4, IP3, IP4);
382         verifyPacketOut(ndpReply, getLocation(5), packetService.packets.get(0));
383     }
384
385     /**
386      * Tests {@link ProxyArpManager#reply(Ethernet, ConnectPoint)} in the case where the
387      * destination host is not known.
388      * Verifies the ARP request is flooded out the correct edge ports.
389      */
390     @Test
391     public void testReplyUnknown() {
392         isEdgePointReturn = true;
393
394         Host requestor = new DefaultHost(PID, HID2, MAC2, VLAN1, getLocation(5),
395                 Collections.singleton(IP2));
396
397         expect(hostService.getHostsByIp(IP1))
398                 .andReturn(Collections.emptySet());
399         expect(interfaceService.getInterfacesByIp(IP2))
400                 .andReturn(Collections.emptySet());
401         expect(hostService.getHost(HID2)).andReturn(requestor);
402
403         replay(hostService);
404         replay(interfaceService);
405
406         Ethernet arpRequest = buildArp(ARP.OP_REQUEST, MAC2, null, IP2, IP1);
407
408         //Setup the set of edge ports to be used in the reply method
409         getEdgePointsNoArg = Lists.newLinkedList();
410         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("5"), PortNumber.portNumber(1)));
411         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("4"), PortNumber.portNumber(1)));
412
413         proxyArp.reply(arpRequest, getLocation(6));
414
415         verifyFlood(arpRequest);
416     }
417
418     /**
419      * Tests {@link ProxyArpManager#reply(Ethernet, ConnectPoint)} in the case where the
420      * destination host is not known.
421      * Verifies the NDP request is flooded out the correct edge ports.
422      */
423     @Test
424     public void testReplyUnknownIpv6() {
425         isEdgePointReturn = true;
426
427         Host requestor = new DefaultHost(PID, HID4, MAC4, VLAN1, getLocation(5),
428                                          Collections.singleton(IP4));
429
430         expect(hostService.getHostsByIp(IP3))
431                 .andReturn(Collections.emptySet());
432         expect(interfaceService.getInterfacesByIp(IP4))
433                 .andReturn(Collections.emptySet());
434         expect(hostService.getHost(HID4)).andReturn(requestor);
435
436         replay(hostService);
437         replay(interfaceService);
438
439         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
440                                        MAC4, SOLICITED_MAC3,
441                                        IP4, IP3);
442
443         //Setup the set of edge ports to be used in the reply method
444         getEdgePointsNoArg = Lists.newLinkedList();
445         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("5"), PortNumber.portNumber(1)));
446         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("4"), PortNumber.portNumber(1)));
447
448         proxyArp.reply(ndpRequest, getLocation(6));
449
450         verifyFlood(ndpRequest);
451     }
452
453     /**
454      * Tests {@link ProxyArpManager#reply(Ethernet, ConnectPoint)} in the case where the
455      * destination host is known for that IP address, but is not on the same
456      * VLAN as the source host.
457      * Verifies the ARP request is flooded out the correct edge ports.
458      */
459     @Test
460     public void testReplyDifferentVlan() {
461
462         Host replyer = new DefaultHost(PID, HID1, MAC1, VLAN2, getLocation(4),
463                 Collections.singleton(IP1));
464
465         Host requestor = new DefaultHost(PID, HID2, MAC2, VLAN1, getLocation(5),
466                 Collections.singleton(IP2));
467
468         expect(hostService.getHostsByIp(IP1))
469                 .andReturn(Collections.singleton(replyer));
470         expect(interfaceService.getInterfacesByIp(IP2))
471                 .andReturn(Collections.emptySet());
472         expect(hostService.getHost(HID2)).andReturn(requestor);
473
474         replay(hostService);
475         replay(interfaceService);
476
477         Ethernet arpRequest = buildArp(ARP.OP_REQUEST, MAC2, null, IP2, IP1);
478
479         //Setup for flood test
480         getEdgePointsNoArg = Lists.newLinkedList();
481         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("5"), PortNumber.portNumber(1)));
482         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("4"), PortNumber.portNumber(1)));
483         proxyArp.reply(arpRequest, getLocation(6));
484
485         verifyFlood(arpRequest);
486     }
487
488     /**
489      * Tests {@link ProxyArpManager#reply(Ethernet, ConnectPoint)} in the case where the
490      * destination host is known for that IP address, but is not on the same
491      * VLAN as the source host.
492      * Verifies the NDP request is flooded out the correct edge ports.
493      */
494     @Test
495     public void testReplyDifferentVlanIpv6() {
496
497         Host replyer = new DefaultHost(PID, HID3, MAC3, VLAN2, getLocation(4),
498                                        Collections.singleton(IP3));
499
500         Host requestor = new DefaultHost(PID, HID4, MAC4, VLAN1, getLocation(5),
501                                          Collections.singleton(IP4));
502
503         expect(hostService.getHostsByIp(IP3))
504                 .andReturn(Collections.singleton(replyer));
505         expect(interfaceService.getInterfacesByIp(IP4))
506                 .andReturn(Collections.emptySet());
507         expect(hostService.getHost(HID4)).andReturn(requestor);
508
509         replay(hostService);
510         replay(interfaceService);
511
512         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
513                                        MAC4, SOLICITED_MAC3,
514                                        IP4, IP3);
515
516         //Setup for flood test
517         getEdgePointsNoArg = Lists.newLinkedList();
518         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("5"), PortNumber.portNumber(1)));
519         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("4"), PortNumber.portNumber(1)));
520         proxyArp.reply(ndpRequest, getLocation(6));
521
522         verifyFlood(ndpRequest);
523     }
524
525     /**
526      * Test ARP request from external network to an internal host.
527      */
528     @Test
529     public void testReplyToRequestForUs() {
530         Ip4Address theirIp = Ip4Address.valueOf("10.0.1.254");
531         Ip4Address ourFirstIp = Ip4Address.valueOf("10.0.1.1");
532         Ip4Address ourSecondIp = Ip4Address.valueOf("10.0.2.1");
533         MacAddress firstMac = MacAddress.valueOf(1L);
534         MacAddress secondMac = MacAddress.valueOf(2L);
535
536         Host requestor = new DefaultHost(PID, HID2, MAC2, VLAN1, LOC1,
537                 Collections.singleton(theirIp));
538
539         expect(hostService.getHost(HID2)).andReturn(requestor);
540         replay(hostService);
541         replay(interfaceService);
542
543         Ethernet arpRequest = buildArp(ARP.OP_REQUEST, MAC2, null, theirIp, ourFirstIp);
544         isEdgePointReturn = true;
545         proxyArp.reply(arpRequest, LOC1);
546
547         assertEquals(1, packetService.packets.size());
548         Ethernet arpReply = buildArp(ARP.OP_REPLY, firstMac, MAC2, ourFirstIp, theirIp);
549         verifyPacketOut(arpReply, LOC1, packetService.packets.get(0));
550
551         // Test a request for the second address on that port
552         packetService.packets.clear();
553         arpRequest = buildArp(ARP.OP_REQUEST, MAC2, null, theirIp, ourSecondIp);
554
555         proxyArp.reply(arpRequest, LOC1);
556
557         assertEquals(1, packetService.packets.size());
558         arpReply = buildArp(ARP.OP_REPLY, secondMac, MAC2, ourSecondIp, theirIp);
559         verifyPacketOut(arpReply, LOC1, packetService.packets.get(0));
560     }
561
562     /**
563      * Test NDP request from external network to an internal host.
564      */
565     @Test
566     public void testReplyToRequestForUsIpv6() {
567         Ip6Address theirIp = Ip6Address.valueOf("1000::ffff");
568         Ip6Address ourFirstIp = Ip6Address.valueOf("1000::1");
569         Ip6Address ourSecondIp = Ip6Address.valueOf("2000::1");
570         MacAddress firstMac = MacAddress.valueOf(1L);
571         MacAddress secondMac = MacAddress.valueOf(2L);
572
573         Host requestor = new DefaultHost(PID, HID2, MAC2, VLAN1, LOC1,
574                                          Collections.singleton(theirIp));
575
576         expect(hostService.getHost(HID2)).andReturn(requestor);
577         expect(hostService.getHostsByIp(ourFirstIp))
578                 .andReturn(Collections.singleton(requestor));
579         replay(hostService);
580         replay(interfaceService);
581
582         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
583                                        MAC2,
584                                        MacAddress.valueOf("33:33:ff:00:00:01"),
585                                        theirIp,
586                                        ourFirstIp);
587         isEdgePointReturn = true;
588         proxyArp.reply(ndpRequest, LOC1);
589         assertEquals(1, packetService.packets.size());
590
591         Ethernet ndpReply = buildNDP(ICMP6.NEIGHBOR_ADVERTISEMENT,
592                                      firstMac,
593                                      MAC2,
594                                      ourFirstIp,
595                                      theirIp);
596         verifyPacketOut(ndpReply, LOC1, packetService.packets.get(0));
597
598         // Test a request for the second address on that port
599         packetService.packets.clear();
600         ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
601                               MAC2,
602                                        MacAddress.valueOf("33:33:ff:00:00:01"),
603                                        theirIp,
604                                        ourSecondIp);
605         proxyArp.reply(ndpRequest, LOC1);
606         assertEquals(1, packetService.packets.size());
607
608         ndpReply = buildNDP(ICMP6.NEIGHBOR_ADVERTISEMENT,
609                                      secondMac,
610                                      MAC2,
611                                      ourSecondIp,
612                                      theirIp);
613         verifyPacketOut(ndpReply, LOC1, packetService.packets.get(0));
614     }
615
616     /**
617      * Request for a valid external IPv4 address but coming in the wrong port.
618      */
619     @Test
620     public void testReplyExternalPortBadRequest() {
621         replay(hostService); // no further host service expectations
622         replay(interfaceService);
623
624         Ip4Address theirIp = Ip4Address.valueOf("10.0.1.254");
625
626         // Request for a valid external IP address but coming in the wrong port
627         Ethernet arpRequest = buildArp(ARP.OP_REQUEST, MAC1, null, theirIp,
628                 Ip4Address.valueOf("10.0.3.1"));
629         proxyArp.reply(arpRequest, LOC1);
630         assertEquals(0, packetService.packets.size());
631
632         // Request for a valid internal IP address but coming in an external port
633         packetService.packets.clear();
634         arpRequest = buildArp(ARP.OP_REQUEST, MAC1, null, theirIp, IP1);
635         proxyArp.reply(arpRequest, LOC1);
636         assertEquals(0, packetService.packets.size());
637     }
638
639     /**
640      * Request for a valid external IPv6 address but coming in the wrong port.
641      */
642     @Test
643     public void testReplyExternalPortBadRequestIpv6() {
644         replay(hostService); // no further host service expectations
645         replay(interfaceService);
646
647         Ip6Address theirIp = Ip6Address.valueOf("1000::ffff");
648
649         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
650                                        MAC1,
651                                        MacAddress.valueOf("33:33:ff:00:00:01"),
652                                        theirIp,
653                                        Ip6Address.valueOf("3000::1"));
654         proxyArp.reply(ndpRequest, LOC1);
655         assertEquals(0, packetService.packets.size());
656
657         // Request for a valid internal IP address but coming in an external port
658         packetService.packets.clear();
659         ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
660                                        MAC1,
661                                        MacAddress.valueOf("33:33:ff:00:00:01"),
662                                        theirIp,
663                                        IP3);
664         proxyArp.reply(ndpRequest, LOC1);
665         assertEquals(0, packetService.packets.size());
666     }
667
668     /**
669      * Test ARP request from internal network to an external host.
670      */
671     @Test
672     public void testReplyToRequestFromUs() {
673         Ip4Address ourIp = Ip4Address.valueOf("10.0.1.1");
674         MacAddress ourMac = MacAddress.valueOf(1L);
675         Ip4Address theirIp = Ip4Address.valueOf("10.0.1.100");
676
677         expect(hostService.getHostsByIp(theirIp)).andReturn(Collections.emptySet());
678         expect(interfaceService.getInterfacesByIp(ourIp))
679                 .andReturn(Collections.singleton(new Interface(getLocation(1),
680                         Collections.singleton(new InterfaceIpAddress(ourIp, IpPrefix.valueOf("10.0.1.1/24"))),
681                         ourMac, VLAN1)));
682         expect(hostService.getHost(HostId.hostId(ourMac, VLAN1))).andReturn(null);
683         replay(hostService);
684         replay(interfaceService);
685
686         // This is a request from something inside our network (like a BGP
687         // daemon) to an external host.
688         Ethernet arpRequest = buildArp(ARP.OP_REQUEST, ourMac, null, ourIp, theirIp);
689         //Ensure the packet is allowed through (it is not to an internal port)
690         isEdgePointReturn = true;
691
692         proxyArp.reply(arpRequest, getLocation(5));
693         assertEquals(1, packetService.packets.size());
694         verifyPacketOut(arpRequest, getLocation(1), packetService.packets.get(0));
695
696         // The same request from a random external port should fail
697         packetService.packets.clear();
698         proxyArp.reply(arpRequest, getLocation(2));
699         assertEquals(0, packetService.packets.size());
700     }
701
702     /**
703      * Test NDP request from internal network to an external host.
704      */
705     @Test
706     public void testReplyToRequestFromUsIpv6() {
707         Ip6Address ourIp = Ip6Address.valueOf("1000::1");
708         MacAddress ourMac = MacAddress.valueOf(1L);
709         Ip6Address theirIp = Ip6Address.valueOf("1000::100");
710
711         expect(hostService.getHostsByIp(theirIp)).andReturn(Collections.emptySet());
712         expect(interfaceService.getInterfacesByIp(ourIp))
713                 .andReturn(Collections.singleton(new Interface(getLocation(1),
714                         Collections.singleton(new InterfaceIpAddress(
715                                 ourIp,
716                                 IpPrefix.valueOf("1000::1/64"))),
717                                 ourMac,
718                                 VLAN1)));
719         expect(hostService.getHost(HostId.hostId(ourMac, VLAN1))).andReturn(null);
720         replay(hostService);
721         replay(interfaceService);
722
723         // This is a request from something inside our network (like a BGP
724         // daemon) to an external host.
725         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
726                                        ourMac,
727                                        MacAddress.valueOf("33:33:ff:00:00:01"),
728                                        ourIp,
729                                        theirIp);
730
731         //Ensure the packet is allowed through (it is not to an internal port)
732         isEdgePointReturn = true;
733
734         proxyArp.reply(ndpRequest, getLocation(5));
735         assertEquals(1, packetService.packets.size());
736         verifyPacketOut(ndpRequest, getLocation(1), packetService.packets.get(0));
737
738         // The same request from a random external port should fail
739         packetService.packets.clear();
740         proxyArp.reply(ndpRequest, getLocation(2));
741         assertEquals(0, packetService.packets.size());
742     }
743
744     /**
745      * Tests {@link ProxyArpManager#forward(Ethernet, ConnectPoint)} in the case where the
746      * destination host is known.
747      * Verifies the correct ARP request is sent out the correct port.
748      */
749     @Test
750     public void testForwardToHost() {
751         Host host1 = new DefaultHost(PID, HID1, MAC1, VLAN1, LOC1,
752                 Collections.singleton(IP1));
753         Host host2 = new DefaultHost(PID, HID2, MAC2, VLAN1, LOC2,
754                                      Collections.singleton(IP2));
755
756         expect(hostService.getHost(HID1)).andReturn(host1);
757         expect(hostService.getHost(HID2)).andReturn(host2);
758         replay(hostService);
759         replay(interfaceService);
760
761         Ethernet arpRequest = buildArp(ARP.OP_REPLY, MAC2, MAC1, IP2, IP1);
762
763         proxyArp.forward(arpRequest, LOC2);
764
765         assertEquals(1, packetService.packets.size());
766         OutboundPacket packet = packetService.packets.get(0);
767
768         verifyPacketOut(arpRequest, LOC1, packet);
769     }
770
771     /**
772      * Tests {@link ProxyArpManager#forward(Ethernet, ConnectPoint)} in the case where the
773      * destination host is known.
774      * Verifies the correct ARP request is sent out the correct port.
775      */
776     @Test
777     public void testForwardToHostIpv6() {
778         Host host1 = new DefaultHost(PID, HID3, MAC3, VLAN1, LOC1,
779                                      Collections.singleton(IP3));
780         Host host2 = new DefaultHost(PID, HID4, MAC4, VLAN1, LOC2,
781                                      Collections.singleton(IP4));
782
783         expect(hostService.getHost(SOLICITED_HID3)).andReturn(host1);
784         expect(hostService.getHost(HID4)).andReturn(host2);
785         replay(hostService);
786         replay(interfaceService);
787
788         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
789                                        MAC4, SOLICITED_MAC3,
790                                        IP4, IP3);
791
792         proxyArp.forward(ndpRequest, LOC2);
793
794         assertEquals(1, packetService.packets.size());
795         OutboundPacket packet = packetService.packets.get(0);
796
797         verifyPacketOut(ndpRequest, LOC1, packet);
798     }
799
800     /**
801      * Tests {@link ProxyArpManager#forward(Ethernet, ConnectPoint)} in the case where the
802      * destination host is not known.
803      * Verifies the correct ARP request is flooded out the correct edge ports.
804      */
805     @Test
806     public void testForwardFlood() {
807         expect(hostService.getHost(HID1)).andReturn(null);
808         replay(hostService);
809         replay(interfaceService);
810
811         Ethernet arpRequest = buildArp(ARP.OP_REPLY, MAC2, MAC1, IP2, IP1);
812
813         //populate the list of edges when so that when forward hits flood in the manager it contains the values
814         //that should continue on
815         getEdgePointsNoArg = Lists.newLinkedList();
816         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("3"), PortNumber.portNumber(1)));
817         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("5"), PortNumber.portNumber(1)));
818         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("4"), PortNumber.portNumber(1)));
819
820         proxyArp.forward(arpRequest, getLocation(6));
821
822         verifyFlood(arpRequest);
823     }
824
825     /**
826      * Tests {@link ProxyArpManager#forward(Ethernet, ConnectPoint)} in the case where the
827      * destination host is not known.
828      * Verifies the correct NDP request is flooded out the correct edge ports.
829      */
830     @Test
831     public void testForwardFloodIpv6() {
832         expect(hostService.getHost(SOLICITED_HID3)).andReturn(null);
833         replay(hostService);
834         replay(interfaceService);
835
836         Ethernet ndpRequest = buildNDP(ICMP6.NEIGHBOR_SOLICITATION,
837                                        MAC4, SOLICITED_MAC3,
838                                        IP4, IP3);
839
840         //populate the list of edges when so that when forward hits flood in the manager it contains the values
841         //that should continue on
842         getEdgePointsNoArg = Lists.newLinkedList();
843         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("3"), PortNumber.portNumber(1)));
844         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("5"), PortNumber.portNumber(1)));
845         getEdgePointsNoArg.add(new ConnectPoint(DeviceId.deviceId("4"), PortNumber.portNumber(1)));
846
847         proxyArp.forward(ndpRequest, getLocation(6));
848
849         verifyFlood(ndpRequest);
850     }
851
852     /**
853      * Verifies that the given packet was flooded out all available edge ports,
854      * except for the input port.
855      *
856      * @param packet the packet that was expected to be flooded
857      */
858     private void verifyFlood(Ethernet packet) {
859         // There should be 1 less than NUM_FLOOD_PORTS; the inPort should be excluded.
860         assertEquals(NUM_FLOOD_PORTS - 1, packetService.packets.size());
861
862         Collections.sort(packetService.packets,
863                 (o1, o2) -> o1.sendThrough().uri().compareTo(o2.sendThrough().uri()));
864
865
866         for (int i = 0; i < NUM_FLOOD_PORTS - 1; i++) {
867             ConnectPoint cp = new ConnectPoint(getDeviceId(NUM_ADDRESS_PORTS + i + 1),
868                     PortNumber.portNumber(1));
869
870             OutboundPacket outboundPacket = packetService.packets.get(i);
871             verifyPacketOut(packet, cp, outboundPacket);
872         }
873     }
874
875     /**
876      * Verifies the given packet was sent out the given port.
877      *
878      * @param expected the packet that was expected to be sent
879      * @param outPort  the port the packet was expected to be sent out
880      * @param actual   the actual OutboundPacket to verify
881      */
882     private void verifyPacketOut(Ethernet expected, ConnectPoint outPort,
883                                  OutboundPacket actual) {
884         assertArrayEquals(expected.serialize(), actual.data().array());
885         assertEquals(1, actual.treatment().immediate().size());
886         assertEquals(outPort.deviceId(), actual.sendThrough());
887         Instruction instruction = actual.treatment().immediate().get(0);
888         assertTrue(instruction instanceof OutputInstruction);
889         assertEquals(outPort.port(), ((OutputInstruction) instruction).port());
890     }
891
892     /**
893      * Returns the device ID of the ith device.
894      *
895      * @param i device to get the ID of
896      * @return the device ID
897      */
898     private static DeviceId getDeviceId(int i) {
899         return DeviceId.deviceId("" + i);
900     }
901
902     private static HostLocation getLocation(int i) {
903         return new HostLocation(new ConnectPoint(getDeviceId(i), P1), 123L);
904     }
905
906     /**
907      * Builds an ARP packet with the given parameters.
908      *
909      * @param opcode opcode of the ARP packet
910      * @param srcMac source MAC address
911      * @param dstMac destination MAC address, or null if this is a request
912      * @param srcIp  source IP address
913      * @param dstIp  destination IP address
914      * @return the ARP packet
915      */
916     private Ethernet buildArp(short opcode, MacAddress srcMac, MacAddress dstMac,
917                               Ip4Address srcIp, Ip4Address dstIp) {
918         Ethernet eth = new Ethernet();
919
920         if (dstMac == null) {
921             eth.setDestinationMACAddress(MacAddress.BROADCAST);
922         } else {
923             eth.setDestinationMACAddress(dstMac);
924         }
925
926         eth.setSourceMACAddress(srcMac);
927         eth.setEtherType(Ethernet.TYPE_ARP);
928         eth.setVlanID(VLAN1.toShort());
929
930         ARP arp = new ARP();
931         arp.setOpCode(opcode);
932         arp.setProtocolType(ARP.PROTO_TYPE_IP);
933         arp.setHardwareType(ARP.HW_TYPE_ETHERNET);
934
935         arp.setProtocolAddressLength((byte) Ip4Address.BYTE_LENGTH);
936         arp.setHardwareAddressLength((byte) Ethernet.DATALAYER_ADDRESS_LENGTH);
937         arp.setSenderHardwareAddress(srcMac.toBytes());
938
939         if (dstMac == null) {
940             arp.setTargetHardwareAddress(ZERO_MAC_ADDRESS);
941         } else {
942             arp.setTargetHardwareAddress(dstMac.toBytes());
943         }
944
945         arp.setSenderProtocolAddress(srcIp.toOctets());
946         arp.setTargetProtocolAddress(dstIp.toOctets());
947
948         eth.setPayload(arp);
949         return eth;
950     }
951
952     /**
953      * Builds an NDP packet with the given parameters.
954      *
955      * @param type NeighborSolicitation or NeighborAdvertisement
956      * @param srcMac source MAC address
957      * @param dstMac destination MAC address, or null if this is a request
958      * @param srcIp  source IP address
959      * @param dstIp  destination IP address
960      * @return the NDP packet
961      */
962     private Ethernet buildNDP(byte type, MacAddress srcMac, MacAddress dstMac,
963                               Ip6Address srcIp, Ip6Address dstIp) {
964         assertThat(type, anyOf(
965                 is(ICMP6.NEIGHBOR_SOLICITATION),
966                 is(ICMP6.NEIGHBOR_ADVERTISEMENT)
967         ));
968         assertNotNull(srcMac);
969         assertNotNull(dstMac);
970         assertNotNull(srcIp);
971         assertNotNull(dstIp);
972
973         IPacket ndp;
974         if (type == ICMP6.NEIGHBOR_SOLICITATION) {
975             ndp = new NeighborSolicitation().setTargetAddress(dstIp.toOctets());
976         } else {
977             ndp = new NeighborAdvertisement()
978                     .setSolicitedFlag((byte) 1)
979                     .setOverrideFlag((byte) 1)
980                     .setTargetAddress(srcIp.toOctets())
981                     .addOption(NeighborDiscoveryOptions.TYPE_TARGET_LL_ADDRESS,
982                        srcMac.toBytes());
983         }
984
985         ICMP6 icmp6 = new ICMP6();
986         icmp6.setIcmpType(type);
987         icmp6.setIcmpCode((byte) 0);
988         icmp6.setPayload(ndp);
989
990         IPv6 ipv6 = new IPv6();
991         ipv6.setDestinationAddress(dstIp.toOctets());
992         ipv6.setSourceAddress(srcIp.toOctets());
993         ipv6.setNextHeader(IPv6.PROTOCOL_ICMP6);
994         ipv6.setHopLimit((byte) 255);
995         ipv6.setPayload(icmp6);
996
997         Ethernet eth = new Ethernet();
998         eth.setDestinationMACAddress(dstMac);
999         eth.setSourceMACAddress(srcMac);
1000         eth.setEtherType(Ethernet.TYPE_IPV6);
1001         eth.setVlanID(VLAN1.toShort());
1002         eth.setPayload(ipv6);
1003
1004         return eth;
1005     }
1006
1007     /**
1008      * Test PacketService implementation that simply stores OutboundPackets
1009      * passed to {@link #emit(OutboundPacket)} for later verification.
1010      */
1011     class TestPacketService extends PacketServiceAdapter {
1012
1013         List<OutboundPacket> packets = new ArrayList<>();
1014
1015         @Override
1016         public void emit(OutboundPacket packet) {
1017             packets.add(packet);
1018         }
1019
1020     }
1021
1022     class TestEdgePortService extends EdgeManager {
1023
1024         @Override
1025         public boolean isEdgePoint(ConnectPoint connectPoint) {
1026             return isEdgePointReturn;
1027         }
1028
1029         @Override
1030         public Iterable<ConnectPoint> getEdgePoints() {
1031             return getEdgePointsNoArg;
1032         }
1033     }
1034
1035     private class TestProxyArpStoreAdapter implements ProxyArpStore {
1036         @Override
1037         public void forward(ConnectPoint outPort, Host subject, ByteBuffer packet) {
1038             TrafficTreatment tt = DefaultTrafficTreatment.builder().setOutput(outPort.port()).build();
1039             packetService.emit(new DefaultOutboundPacket(outPort.deviceId(), tt, packet));
1040         }
1041
1042         @Override
1043         public void setDelegate(ProxyArpStoreDelegate delegate) {
1044         }
1045     }
1046 }