ip: Replace Sematics for Interface IP addresses
[vpp.git] / test / test_ip6.py
1 #!/usr/bin/env python3
2
3 import socket
4 from socket import inet_pton, inet_ntop
5 import unittest
6
7 from parameterized import parameterized
8 import scapy.compat
9 import scapy.layers.inet6 as inet6
10 from scapy.contrib.mpls import MPLS
11 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_RS, \
12     ICMPv6ND_RA, ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, \
13     ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types, \
14     ICMPv6TimeExceeded, ICMPv6EchoRequest, ICMPv6EchoReply, \
15     IPv6ExtHdrHopByHop, ICMPv6MLReport2, ICMPv6MLDMultAddrRec
16 from scapy.layers.l2 import Ether, Dot1Q
17 from scapy.packet import Raw
18 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, \
19     in6_mactoifaceid
20 from six import moves
21
22 from framework import VppTestCase, VppTestRunner
23 from util import ppp, ip6_normalize, mk_ll_addr
24 from vpp_ip import DpoProto
25 from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, VppIpMRoute, \
26     VppMRoutePath, MRouteItfFlags, MRouteEntryFlags, VppMplsIpBind, \
27     VppMplsRoute, VppMplsTable, VppIpTable, FibPathType, FibPathProto, \
28     VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump
29 from vpp_neighbor import find_nbr, VppNeighbor
30 from vpp_pg_interface import is_ipv6_misc
31 from vpp_sub_interface import VppSubInterface, VppDot1QSubint
32 from vpp_policer import VppPolicer
33 from ipaddress import IPv6Network, IPv6Address
34
35 AF_INET6 = socket.AF_INET6
36
37 try:
38     text_type = unicode
39 except NameError:
40     text_type = str
41
42 NUM_PKTS = 67
43
44
45 class TestIPv6ND(VppTestCase):
46     def validate_ra(self, intf, rx, dst_ip=None):
47         if not dst_ip:
48             dst_ip = intf.remote_ip6
49
50         # unicasted packets must come to the unicast mac
51         self.assertEqual(rx[Ether].dst, intf.remote_mac)
52
53         # and from the router's MAC
54         self.assertEqual(rx[Ether].src, intf.local_mac)
55
56         # the rx'd RA should be addressed to the sender's source
57         self.assertTrue(rx.haslayer(ICMPv6ND_RA))
58         self.assertEqual(in6_ptop(rx[IPv6].dst),
59                          in6_ptop(dst_ip))
60
61         # and come from the router's link local
62         self.assertTrue(in6_islladdr(rx[IPv6].src))
63         self.assertEqual(in6_ptop(rx[IPv6].src),
64                          in6_ptop(mk_ll_addr(intf.local_mac)))
65
66     def validate_na(self, intf, rx, dst_ip=None, tgt_ip=None):
67         if not dst_ip:
68             dst_ip = intf.remote_ip6
69         if not tgt_ip:
70             dst_ip = intf.local_ip6
71
72         # unicasted packets must come to the unicast mac
73         self.assertEqual(rx[Ether].dst, intf.remote_mac)
74
75         # and from the router's MAC
76         self.assertEqual(rx[Ether].src, intf.local_mac)
77
78         # the rx'd NA should be addressed to the sender's source
79         self.assertTrue(rx.haslayer(ICMPv6ND_NA))
80         self.assertEqual(in6_ptop(rx[IPv6].dst),
81                          in6_ptop(dst_ip))
82
83         # and come from the target address
84         self.assertEqual(
85             in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip))
86
87         # Dest link-layer options should have the router's MAC
88         dll = rx[ICMPv6NDOptDstLLAddr]
89         self.assertEqual(dll.lladdr, intf.local_mac)
90
91     def validate_ns(self, intf, rx, tgt_ip):
92         nsma = in6_getnsma(inet_pton(AF_INET6, tgt_ip))
93         dst_ip = inet_ntop(AF_INET6, nsma)
94
95         # NS is broadcast
96         self.assertEqual(rx[Ether].dst, in6_getnsmac(nsma))
97
98         # and from the router's MAC
99         self.assertEqual(rx[Ether].src, intf.local_mac)
100
101         # the rx'd NS should be addressed to an mcast address
102         # derived from the target address
103         self.assertEqual(
104             in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
105
106         # expect the tgt IP in the NS header
107         ns = rx[ICMPv6ND_NS]
108         self.assertEqual(in6_ptop(ns.tgt), in6_ptop(tgt_ip))
109
110         # packet is from the router's local address
111         self.assertEqual(
112             in6_ptop(rx[IPv6].src), intf.local_ip6)
113
114         # Src link-layer options should have the router's MAC
115         sll = rx[ICMPv6NDOptSrcLLAddr]
116         self.assertEqual(sll.lladdr, intf.local_mac)
117
118     def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
119                            filter_out_fn=is_ipv6_misc):
120         intf.add_stream(pkts)
121         self.pg_enable_capture(self.pg_interfaces)
122         self.pg_start()
123         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
124
125         self.assertEqual(len(rx), 1)
126         rx = rx[0]
127         self.validate_ra(intf, rx, dst_ip)
128
129     def send_and_expect_na(self, intf, pkts, remark, dst_ip=None,
130                            tgt_ip=None,
131                            filter_out_fn=is_ipv6_misc):
132         intf.add_stream(pkts)
133         self.pg_enable_capture(self.pg_interfaces)
134         self.pg_start()
135         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
136
137         self.assertEqual(len(rx), 1)
138         rx = rx[0]
139         self.validate_na(intf, rx, dst_ip, tgt_ip)
140
141     def send_and_expect_ns(self, tx_intf, rx_intf, pkts, tgt_ip,
142                            filter_out_fn=is_ipv6_misc):
143         self.vapi.cli("clear trace")
144         tx_intf.add_stream(pkts)
145         self.pg_enable_capture(self.pg_interfaces)
146         self.pg_start()
147         rx = rx_intf.get_capture(1, filter_out_fn=filter_out_fn)
148
149         self.assertEqual(len(rx), 1)
150         rx = rx[0]
151         self.validate_ns(rx_intf, rx, tgt_ip)
152
153     def verify_ip(self, rx, smac, dmac, sip, dip):
154         ether = rx[Ether]
155         self.assertEqual(ether.dst, dmac)
156         self.assertEqual(ether.src, smac)
157
158         ip = rx[IPv6]
159         self.assertEqual(ip.src, sip)
160         self.assertEqual(ip.dst, dip)
161
162
163 class TestIPv6(TestIPv6ND):
164     """ IPv6 Test Case """
165
166     @classmethod
167     def setUpClass(cls):
168         super(TestIPv6, cls).setUpClass()
169
170     @classmethod
171     def tearDownClass(cls):
172         super(TestIPv6, cls).tearDownClass()
173
174     def setUp(self):
175         """
176         Perform test setup before test case.
177
178         **Config:**
179             - create 3 pg interfaces
180                 - untagged pg0 interface
181                 - Dot1Q subinterface on pg1
182                 - Dot1AD subinterface on pg2
183             - setup interfaces:
184                 - put it into UP state
185                 - set IPv6 addresses
186                 - resolve neighbor address using NDP
187             - configure 200 fib entries
188
189         :ivar list interfaces: pg interfaces and subinterfaces.
190         :ivar dict flows: IPv4 packet flows in test.
191
192         *TODO:* Create AD sub interface
193         """
194         super(TestIPv6, self).setUp()
195
196         # create 3 pg interfaces
197         self.create_pg_interfaces(range(3))
198
199         # create 2 subinterfaces for p1 and pg2
200         self.sub_interfaces = [
201             VppDot1QSubint(self, self.pg1, 100),
202             VppDot1QSubint(self, self.pg2, 200)
203             # TODO: VppDot1ADSubint(self, self.pg2, 200, 300, 400)
204         ]
205
206         # packet flows mapping pg0 -> pg1.sub, pg2.sub, etc.
207         self.flows = dict()
208         self.flows[self.pg0] = [self.pg1.sub_if, self.pg2.sub_if]
209         self.flows[self.pg1.sub_if] = [self.pg0, self.pg2.sub_if]
210         self.flows[self.pg2.sub_if] = [self.pg0, self.pg1.sub_if]
211
212         # packet sizes
213         self.pg_if_packet_sizes = [64, 1500, 9020]
214
215         self.interfaces = list(self.pg_interfaces)
216         self.interfaces.extend(self.sub_interfaces)
217
218         # setup all interfaces
219         for i in self.interfaces:
220             i.admin_up()
221             i.config_ip6()
222             i.resolve_ndp()
223
224     def tearDown(self):
225         """Run standard test teardown and log ``show ip6 neighbors``."""
226         for i in self.interfaces:
227             i.unconfig_ip6()
228             i.admin_down()
229         for i in self.sub_interfaces:
230             i.remove_vpp_config()
231
232         super(TestIPv6, self).tearDown()
233         if not self.vpp_dead:
234             self.logger.info(self.vapi.cli("show ip6 neighbors"))
235             # info(self.vapi.cli("show ip6 fib"))  # many entries
236
237     def modify_packet(self, src_if, packet_size, pkt):
238         """Add load, set destination IP and extend packet to required packet
239         size for defined interface.
240
241         :param VppInterface src_if: Interface to create packet for.
242         :param int packet_size: Required packet size.
243         :param Scapy pkt: Packet to be modified.
244         """
245         dst_if_idx = int(packet_size / 10 % 2)
246         dst_if = self.flows[src_if][dst_if_idx]
247         info = self.create_packet_info(src_if, dst_if)
248         payload = self.info_to_payload(info)
249         p = pkt / Raw(payload)
250         p[IPv6].dst = dst_if.remote_ip6
251         info.data = p.copy()
252         if isinstance(src_if, VppSubInterface):
253             p = src_if.add_dot1_layer(p)
254         self.extend_packet(p, packet_size)
255
256         return p
257
258     def create_stream(self, src_if):
259         """Create input packet stream for defined interface.
260
261         :param VppInterface src_if: Interface to create packet stream for.
262         """
263         hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0
264         pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
265                     IPv6(src=src_if.remote_ip6) /
266                     inet6.UDP(sport=1234, dport=1234))
267
268         pkts = [self.modify_packet(src_if, i, pkt_tmpl)
269                 for i in moves.range(self.pg_if_packet_sizes[0],
270                                      self.pg_if_packet_sizes[1], 10)]
271         pkts_b = [self.modify_packet(src_if, i, pkt_tmpl)
272                   for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext,
273                                        self.pg_if_packet_sizes[2] + hdr_ext,
274                                        50)]
275         pkts.extend(pkts_b)
276
277         return pkts
278
279     def verify_capture(self, dst_if, capture):
280         """Verify captured input packet stream for defined interface.
281
282         :param VppInterface dst_if: Interface to verify captured packet stream
283                                     for.
284         :param list capture: Captured packet stream.
285         """
286         self.logger.info("Verifying capture on interface %s" % dst_if.name)
287         last_info = dict()
288         for i in self.interfaces:
289             last_info[i.sw_if_index] = None
290         is_sub_if = False
291         dst_sw_if_index = dst_if.sw_if_index
292         if hasattr(dst_if, 'parent'):
293             is_sub_if = True
294         for packet in capture:
295             if is_sub_if:
296                 # Check VLAN tags and Ethernet header
297                 packet = dst_if.remove_dot1_layer(packet)
298             self.assertTrue(Dot1Q not in packet)
299             try:
300                 ip = packet[IPv6]
301                 udp = packet[inet6.UDP]
302                 payload_info = self.payload_to_info(packet[Raw])
303                 packet_index = payload_info.index
304                 self.assertEqual(payload_info.dst, dst_sw_if_index)
305                 self.logger.debug(
306                     "Got packet on port %s: src=%u (id=%u)" %
307                     (dst_if.name, payload_info.src, packet_index))
308                 next_info = self.get_next_packet_info_for_interface2(
309                     payload_info.src, dst_sw_if_index,
310                     last_info[payload_info.src])
311                 last_info[payload_info.src] = next_info
312                 self.assertTrue(next_info is not None)
313                 self.assertEqual(packet_index, next_info.index)
314                 saved_packet = next_info.data
315                 # Check standard fields
316                 self.assertEqual(
317                     ip.src, saved_packet[IPv6].src)
318                 self.assertEqual(
319                     ip.dst, saved_packet[IPv6].dst)
320                 self.assertEqual(
321                     udp.sport, saved_packet[inet6.UDP].sport)
322                 self.assertEqual(
323                     udp.dport, saved_packet[inet6.UDP].dport)
324             except:
325                 self.logger.error(ppp("Unexpected or invalid packet:", packet))
326                 raise
327         for i in self.interfaces:
328             remaining_packet = self.get_next_packet_info_for_interface2(
329                 i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
330             self.assertTrue(remaining_packet is None,
331                             "Interface %s: Packet expected from interface %s "
332                             "didn't arrive" % (dst_if.name, i.name))
333
334     def test_next_header_anomaly(self):
335         """ IPv6 next header anomaly test
336
337         Test scenario:
338             - ipv6 next header field = Fragment Header (44)
339             - next header is ICMPv6 Echo Request
340             - wait for reassembly
341         """
342         pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
343                IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44) /
344                ICMPv6EchoRequest())
345
346         self.pg0.add_stream(pkt)
347         self.pg_start()
348
349         # wait for reassembly
350         self.sleep(10)
351
352     def test_fib(self):
353         """ IPv6 FIB test
354
355         Test scenario:
356             - Create IPv6 stream for pg0 interface
357             - Create IPv6 tagged streams for pg1's and pg2's subinterface.
358             - Send and verify received packets on each interface.
359         """
360
361         pkts = self.create_stream(self.pg0)
362         self.pg0.add_stream(pkts)
363
364         for i in self.sub_interfaces:
365             pkts = self.create_stream(i)
366             i.parent.add_stream(pkts)
367
368         self.pg_enable_capture(self.pg_interfaces)
369         self.pg_start()
370
371         pkts = self.pg0.get_capture()
372         self.verify_capture(self.pg0, pkts)
373
374         for i in self.sub_interfaces:
375             pkts = i.parent.get_capture()
376             self.verify_capture(i, pkts)
377
378     def test_ns(self):
379         """ IPv6 Neighbour Solicitation Exceptions
380
381         Test scenario:
382            - Send an NS Sourced from an address not covered by the link sub-net
383            - Send an NS to an mcast address the router has not joined
384            - Send NS for a target address the router does not onn.
385         """
386
387         #
388         # An NS from a non link source address
389         #
390         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
391         d = inet_ntop(AF_INET6, nsma)
392
393         p = (Ether(dst=in6_getnsmac(nsma)) /
394              IPv6(dst=d, src="2002::2") /
395              ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
396              ICMPv6NDOptSrcLLAddr(
397                  lladdr=self.pg0.remote_mac))
398         pkts = [p]
399
400         self.send_and_assert_no_replies(
401             self.pg0, pkts,
402             "No response to NS source by address not on sub-net")
403
404         #
405         # An NS for sent to a solicited mcast group the router is
406         # not a member of FAILS
407         #
408         if 0:
409             nsma = in6_getnsma(inet_pton(AF_INET6, "fd::ffff"))
410             d = inet_ntop(AF_INET6, nsma)
411
412             p = (Ether(dst=in6_getnsmac(nsma)) /
413                  IPv6(dst=d, src=self.pg0.remote_ip6) /
414                  ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
415                  ICMPv6NDOptSrcLLAddr(
416                      lladdr=self.pg0.remote_mac))
417             pkts = [p]
418
419             self.send_and_assert_no_replies(
420                 self.pg0, pkts,
421                 "No response to NS sent to unjoined mcast address")
422
423         #
424         # An NS whose target address is one the router does not own
425         #
426         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
427         d = inet_ntop(AF_INET6, nsma)
428
429         p = (Ether(dst=in6_getnsmac(nsma)) /
430              IPv6(dst=d, src=self.pg0.remote_ip6) /
431              ICMPv6ND_NS(tgt="fd::ffff") /
432              ICMPv6NDOptSrcLLAddr(
433                  lladdr=self.pg0.remote_mac))
434         pkts = [p]
435
436         self.send_and_assert_no_replies(self.pg0, pkts,
437                                         "No response to NS for unknown target")
438
439         #
440         # A neighbor entry that has no associated FIB-entry
441         #
442         self.pg0.generate_remote_hosts(4)
443         nd_entry = VppNeighbor(self,
444                                self.pg0.sw_if_index,
445                                self.pg0.remote_hosts[2].mac,
446                                self.pg0.remote_hosts[2].ip6,
447                                is_no_fib_entry=1)
448         nd_entry.add_vpp_config()
449
450         #
451         # check we have the neighbor, but no route
452         #
453         self.assertTrue(find_nbr(self,
454                                  self.pg0.sw_if_index,
455                                  self.pg0._remote_hosts[2].ip6))
456         self.assertFalse(find_route(self,
457                                     self.pg0._remote_hosts[2].ip6,
458                                     128))
459
460         #
461         # send an NS from a link local address to the interface's global
462         # address
463         #
464         p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
465              IPv6(
466                  dst=d, src=self.pg0._remote_hosts[2].ip6_ll) /
467              ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
468              ICMPv6NDOptSrcLLAddr(
469                  lladdr=self.pg0.remote_mac))
470
471         self.send_and_expect_na(self.pg0, p,
472                                 "NS from link-local",
473                                 dst_ip=self.pg0._remote_hosts[2].ip6_ll,
474                                 tgt_ip=self.pg0.local_ip6)
475
476         #
477         # we should have learned an ND entry for the peer's link-local
478         # but not inserted a route to it in the FIB
479         #
480         self.assertTrue(find_nbr(self,
481                                  self.pg0.sw_if_index,
482                                  self.pg0._remote_hosts[2].ip6_ll))
483         self.assertFalse(find_route(self,
484                                     self.pg0._remote_hosts[2].ip6_ll,
485                                     128))
486
487         #
488         # An NS to the router's own Link-local
489         #
490         p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
491              IPv6(
492                  dst=d, src=self.pg0._remote_hosts[3].ip6_ll) /
493              ICMPv6ND_NS(tgt=self.pg0.local_ip6_ll) /
494              ICMPv6NDOptSrcLLAddr(
495                  lladdr=self.pg0.remote_mac))
496
497         self.send_and_expect_na(self.pg0, p,
498                                 "NS to/from link-local",
499                                 dst_ip=self.pg0._remote_hosts[3].ip6_ll,
500                                 tgt_ip=self.pg0.local_ip6_ll)
501
502         #
503         # we should have learned an ND entry for the peer's link-local
504         # but not inserted a route to it in the FIB
505         #
506         self.assertTrue(find_nbr(self,
507                                  self.pg0.sw_if_index,
508                                  self.pg0._remote_hosts[3].ip6_ll))
509         self.assertFalse(find_route(self,
510                                     self.pg0._remote_hosts[3].ip6_ll,
511                                     128))
512
513     def test_ns_duplicates(self):
514         """ ND Duplicates"""
515
516         #
517         # Generate some hosts on the LAN
518         #
519         self.pg1.generate_remote_hosts(3)
520
521         #
522         # Add host 1 on pg1 and pg2
523         #
524         ns_pg1 = VppNeighbor(self,
525                              self.pg1.sw_if_index,
526                              self.pg1.remote_hosts[1].mac,
527                              self.pg1.remote_hosts[1].ip6)
528         ns_pg1.add_vpp_config()
529         ns_pg2 = VppNeighbor(self,
530                              self.pg2.sw_if_index,
531                              self.pg2.remote_mac,
532                              self.pg1.remote_hosts[1].ip6)
533         ns_pg2.add_vpp_config()
534
535         #
536         # IP packet destined for pg1 remote host arrives on pg1 again.
537         #
538         p = (Ether(dst=self.pg0.local_mac,
539                    src=self.pg0.remote_mac) /
540              IPv6(src=self.pg0.remote_ip6,
541                   dst=self.pg1.remote_hosts[1].ip6) /
542              inet6.UDP(sport=1234, dport=1234) /
543              Raw())
544
545         self.pg0.add_stream(p)
546         self.pg_enable_capture(self.pg_interfaces)
547         self.pg_start()
548
549         rx1 = self.pg1.get_capture(1)
550
551         self.verify_ip(rx1[0],
552                        self.pg1.local_mac,
553                        self.pg1.remote_hosts[1].mac,
554                        self.pg0.remote_ip6,
555                        self.pg1.remote_hosts[1].ip6)
556
557         #
558         # remove the duplicate on pg1
559         # packet stream should generate NSs out of pg1
560         #
561         ns_pg1.remove_vpp_config()
562
563         self.send_and_expect_ns(self.pg0, self.pg1,
564                                 p, self.pg1.remote_hosts[1].ip6)
565
566         #
567         # Add it back
568         #
569         ns_pg1.add_vpp_config()
570
571         self.pg0.add_stream(p)
572         self.pg_enable_capture(self.pg_interfaces)
573         self.pg_start()
574
575         rx1 = self.pg1.get_capture(1)
576
577         self.verify_ip(rx1[0],
578                        self.pg1.local_mac,
579                        self.pg1.remote_hosts[1].mac,
580                        self.pg0.remote_ip6,
581                        self.pg1.remote_hosts[1].ip6)
582
583     def validate_ra(self, intf, rx, dst_ip=None, src_ip=None,
584                     mtu=9000, pi_opt=None):
585         if not dst_ip:
586             dst_ip = intf.remote_ip6
587         if not src_ip:
588             src_ip = mk_ll_addr(intf.local_mac)
589
590         # unicasted packets must come to the unicast mac
591         self.assertEqual(rx[Ether].dst, intf.remote_mac)
592
593         # and from the router's MAC
594         self.assertEqual(rx[Ether].src, intf.local_mac)
595
596         # the rx'd RA should be addressed to the sender's source
597         self.assertTrue(rx.haslayer(ICMPv6ND_RA))
598         self.assertEqual(in6_ptop(rx[IPv6].dst),
599                          in6_ptop(dst_ip))
600
601         # and come from the router's link local
602         self.assertTrue(in6_islladdr(rx[IPv6].src))
603         self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(src_ip))
604
605         # it should contain the links MTU
606         ra = rx[ICMPv6ND_RA]
607         self.assertEqual(ra[ICMPv6NDOptMTU].mtu, mtu)
608
609         # it should contain the source's link layer address option
610         sll = ra[ICMPv6NDOptSrcLLAddr]
611         self.assertEqual(sll.lladdr, intf.local_mac)
612
613         if not pi_opt:
614             # the RA should not contain prefix information
615             self.assertFalse(ra.haslayer(
616                 ICMPv6NDOptPrefixInfo))
617         else:
618             raos = rx.getlayer(ICMPv6NDOptPrefixInfo, 1)
619
620             # the options are nested in the scapy packet in way that i cannot
621             # decipher how to decode. this 1st layer of option always returns
622             # nested classes, so a direct obj1=obj2 comparison always fails.
623             # however, the getlayer(.., 2) does give one instance.
624             # so we cheat here and construct a new opt instance for comparison
625             rd = ICMPv6NDOptPrefixInfo(
626                 prefixlen=raos.prefixlen,
627                 prefix=raos.prefix,
628                 L=raos.L,
629                 A=raos.A)
630             if type(pi_opt) is list:
631                 for ii in range(len(pi_opt)):
632                     self.assertEqual(pi_opt[ii], rd)
633                     rd = rx.getlayer(
634                         ICMPv6NDOptPrefixInfo, ii + 2)
635             else:
636                 self.assertEqual(pi_opt, raos, 'Expected: %s, received: %s'
637                                  % (pi_opt.show(dump=True),
638                                     raos.show(dump=True)))
639
640     def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
641                            filter_out_fn=is_ipv6_misc,
642                            opt=None,
643                            src_ip=None):
644         self.vapi.cli("clear trace")
645         intf.add_stream(pkts)
646         self.pg_enable_capture(self.pg_interfaces)
647         self.pg_start()
648         rx = intf.get_capture(1, filter_out_fn=filter_out_fn)
649
650         self.assertEqual(len(rx), 1)
651         rx = rx[0]
652         self.validate_ra(intf, rx, dst_ip, src_ip=src_ip, pi_opt=opt)
653
654     def test_rs(self):
655         """ IPv6 Router Solicitation Exceptions
656
657         Test scenario:
658         """
659
660         #
661         # Before we begin change the IPv6 RA responses to use the unicast
662         # address - that way we will not confuse them with the periodic
663         # RAs which go to the mcast address
664         # Sit and wait for the first periodic RA.
665         #
666         # TODO
667         #
668         self.pg0.ip6_ra_config(send_unicast=1)
669
670         #
671         # An RS from a link source address
672         #  - expect an RA in return
673         #
674         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
675              IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
676              ICMPv6ND_RS())
677         pkts = [p]
678         self.send_and_expect_ra(self.pg0, pkts, "Genuine RS")
679
680         #
681         # For the next RS sent the RA should be rate limited
682         #
683         self.send_and_assert_no_replies(self.pg0, pkts, "RA rate limited")
684
685         #
686         # When we reconfigure the IPv6 RA config,
687         # we reset the RA rate limiting,
688         # so we need to do this before each test below so as not to drop
689         # packets for rate limiting reasons. Test this works here.
690         #
691         self.pg0.ip6_ra_config(send_unicast=1)
692         self.send_and_expect_ra(self.pg0, pkts, "Rate limit reset RS")
693
694         #
695         # An RS sent from a non-link local source
696         #
697         self.pg0.ip6_ra_config(send_unicast=1)
698         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
699              IPv6(dst=self.pg0.local_ip6,
700                   src="2002::ffff") /
701              ICMPv6ND_RS())
702         pkts = [p]
703         self.send_and_assert_no_replies(self.pg0, pkts,
704                                         "RS from non-link source")
705
706         #
707         # Source an RS from a link local address
708         #
709         self.pg0.ip6_ra_config(send_unicast=1)
710         ll = mk_ll_addr(self.pg0.remote_mac)
711         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
712              IPv6(dst=self.pg0.local_ip6, src=ll) /
713              ICMPv6ND_RS())
714         pkts = [p]
715         self.send_and_expect_ra(self.pg0, pkts,
716                                 "RS sourced from link-local",
717                                 dst_ip=ll)
718
719         #
720         # Send the RS multicast
721         #
722         self.pg0.ip6_ra_config(send_unicast=1)
723         dmac = in6_getnsmac(inet_pton(AF_INET6, "ff02::2"))
724         ll = mk_ll_addr(self.pg0.remote_mac)
725         p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
726              IPv6(dst="ff02::2", src=ll) /
727              ICMPv6ND_RS())
728         pkts = [p]
729         self.send_and_expect_ra(self.pg0, pkts,
730                                 "RS sourced from link-local",
731                                 dst_ip=ll)
732
733         #
734         # Source from the unspecified address ::. This happens when the RS
735         # is sent before the host has a configured address/sub-net,
736         # i.e. auto-config. Since the sender has no IP address, the reply
737         # comes back mcast - so the capture needs to not filter this.
738         # If we happen to pick up the periodic RA at this point then so be it,
739         # it's not an error.
740         #
741         self.pg0.ip6_ra_config(send_unicast=1, suppress=1)
742         p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
743              IPv6(dst="ff02::2", src="::") /
744              ICMPv6ND_RS())
745         pkts = [p]
746         self.send_and_expect_ra(self.pg0, pkts,
747                                 "RS sourced from unspecified",
748                                 dst_ip="ff02::1",
749                                 filter_out_fn=None)
750
751         #
752         # Configure The RA to announce the links prefix
753         #
754         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
755                                self.pg0.local_ip6_prefix_len))
756
757         #
758         # RAs should now contain the prefix information option
759         #
760         opt = ICMPv6NDOptPrefixInfo(
761             prefixlen=self.pg0.local_ip6_prefix_len,
762             prefix=self.pg0.local_ip6,
763             L=1,
764             A=1)
765
766         self.pg0.ip6_ra_config(send_unicast=1)
767         ll = mk_ll_addr(self.pg0.remote_mac)
768         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
769              IPv6(dst=self.pg0.local_ip6, src=ll) /
770              ICMPv6ND_RS())
771         self.send_and_expect_ra(self.pg0, p,
772                                 "RA with prefix-info",
773                                 dst_ip=ll,
774                                 opt=opt)
775
776         #
777         # Change the prefix info to not off-link
778         #  L-flag is clear
779         #
780         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
781                                self.pg0.local_ip6_prefix_len),
782                                off_link=1)
783
784         opt = ICMPv6NDOptPrefixInfo(
785             prefixlen=self.pg0.local_ip6_prefix_len,
786             prefix=self.pg0.local_ip6,
787             L=0,
788             A=1)
789
790         self.pg0.ip6_ra_config(send_unicast=1)
791         self.send_and_expect_ra(self.pg0, p,
792                                 "RA with Prefix info with L-flag=0",
793                                 dst_ip=ll,
794                                 opt=opt)
795
796         #
797         # Change the prefix info to not off-link, no-autoconfig
798         #  L and A flag are clear in the advert
799         #
800         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
801                                self.pg0.local_ip6_prefix_len),
802                                off_link=1,
803                                no_autoconfig=1)
804
805         opt = ICMPv6NDOptPrefixInfo(
806             prefixlen=self.pg0.local_ip6_prefix_len,
807             prefix=self.pg0.local_ip6,
808             L=0,
809             A=0)
810
811         self.pg0.ip6_ra_config(send_unicast=1)
812         self.send_and_expect_ra(self.pg0, p,
813                                 "RA with Prefix info with A & L-flag=0",
814                                 dst_ip=ll,
815                                 opt=opt)
816
817         #
818         # Change the flag settings back to the defaults
819         #  L and A flag are set in the advert
820         #
821         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
822                                self.pg0.local_ip6_prefix_len))
823
824         opt = ICMPv6NDOptPrefixInfo(
825             prefixlen=self.pg0.local_ip6_prefix_len,
826             prefix=self.pg0.local_ip6,
827             L=1,
828             A=1)
829
830         self.pg0.ip6_ra_config(send_unicast=1)
831         self.send_and_expect_ra(self.pg0, p,
832                                 "RA with Prefix info",
833                                 dst_ip=ll,
834                                 opt=opt)
835
836         #
837         # Change the prefix info to not off-link, no-autoconfig
838         #  L and A flag are clear in the advert
839         #
840         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
841                                self.pg0.local_ip6_prefix_len),
842                                off_link=1,
843                                no_autoconfig=1)
844
845         opt = ICMPv6NDOptPrefixInfo(
846             prefixlen=self.pg0.local_ip6_prefix_len,
847             prefix=self.pg0.local_ip6,
848             L=0,
849             A=0)
850
851         self.pg0.ip6_ra_config(send_unicast=1)
852         self.send_and_expect_ra(self.pg0, p,
853                                 "RA with Prefix info with A & L-flag=0",
854                                 dst_ip=ll,
855                                 opt=opt)
856
857         #
858         # Use the reset to defaults option to revert to defaults
859         #  L and A flag are clear in the advert
860         #
861         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
862                                self.pg0.local_ip6_prefix_len),
863                                use_default=1)
864
865         opt = ICMPv6NDOptPrefixInfo(
866             prefixlen=self.pg0.local_ip6_prefix_len,
867             prefix=self.pg0.local_ip6,
868             L=1,
869             A=1)
870
871         self.pg0.ip6_ra_config(send_unicast=1)
872         self.send_and_expect_ra(self.pg0, p,
873                                 "RA with Prefix reverted to defaults",
874                                 dst_ip=ll,
875                                 opt=opt)
876
877         #
878         # Advertise Another prefix. With no L-flag/A-flag
879         #
880         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6,
881                                self.pg1.local_ip6_prefix_len),
882                                off_link=1,
883                                no_autoconfig=1)
884
885         opt = [ICMPv6NDOptPrefixInfo(
886             prefixlen=self.pg0.local_ip6_prefix_len,
887             prefix=self.pg0.local_ip6,
888             L=1,
889             A=1),
890             ICMPv6NDOptPrefixInfo(
891                 prefixlen=self.pg1.local_ip6_prefix_len,
892                 prefix=self.pg1.local_ip6,
893                 L=0,
894                 A=0)]
895
896         self.pg0.ip6_ra_config(send_unicast=1)
897         ll = mk_ll_addr(self.pg0.remote_mac)
898         p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
899              IPv6(dst=self.pg0.local_ip6, src=ll) /
900              ICMPv6ND_RS())
901         self.send_and_expect_ra(self.pg0, p,
902                                 "RA with multiple Prefix infos",
903                                 dst_ip=ll,
904                                 opt=opt)
905
906         #
907         # Remove the first prefix-info - expect the second is still in the
908         # advert
909         #
910         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
911                                self.pg0.local_ip6_prefix_len),
912                                is_no=1)
913
914         opt = ICMPv6NDOptPrefixInfo(
915             prefixlen=self.pg1.local_ip6_prefix_len,
916             prefix=self.pg1.local_ip6,
917             L=0,
918             A=0)
919
920         self.pg0.ip6_ra_config(send_unicast=1)
921         self.send_and_expect_ra(self.pg0, p,
922                                 "RA with Prefix reverted to defaults",
923                                 dst_ip=ll,
924                                 opt=opt)
925
926         #
927         # Remove the second prefix-info - expect no prefix-info in the adverts
928         #
929         self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6,
930                                self.pg1.local_ip6_prefix_len),
931                                is_no=1)
932
933         #
934         # change the link's link local, so we know that works too.
935         #
936         self.vapi.sw_interface_ip6_set_link_local_address(
937             sw_if_index=self.pg0.sw_if_index,
938             ip="fe80::88")
939
940         self.pg0.ip6_ra_config(send_unicast=1)
941         self.send_and_expect_ra(self.pg0, p,
942                                 "RA with Prefix reverted to defaults",
943                                 dst_ip=ll,
944                                 src_ip="fe80::88")
945
946         #
947         # Reset the periodic advertisements back to default values
948         #
949         self.pg0.ip6_ra_config(no=1, suppress=1, send_unicast=0)
950
951     def test_mld(self):
952         """ MLD Report """
953         #
954         # test one MLD is sent after applying an IPv6 Address on an interface
955         #
956         self.pg_enable_capture(self.pg_interfaces)
957         self.pg_start()
958
959         subitf = VppDot1QSubint(self, self.pg1, 99)
960
961         subitf.admin_up()
962         subitf.config_ip6()
963
964         rxs = self.pg1._get_capture(timeout=4, filter_out_fn=None)
965
966         #
967         # hunt for the MLD on vlan 99
968         #
969         for rx in rxs:
970             # make sure ipv6 packets with hop by hop options have
971             # correct checksums
972             self.assert_packet_checksums_valid(rx)
973             if rx.haslayer(IPv6ExtHdrHopByHop) and \
974                rx.haslayer(Dot1Q) and \
975                rx[Dot1Q].vlan == 99:
976                 mld = rx[ICMPv6MLReport2]
977
978         self.assertEqual(mld.records_number, 4)
979
980
981 class TestIPv6IfAddrRoute(VppTestCase):
982     """ IPv6 Interface Addr Route Test Case """
983
984     @classmethod
985     def setUpClass(cls):
986         super(TestIPv6IfAddrRoute, cls).setUpClass()
987
988     @classmethod
989     def tearDownClass(cls):
990         super(TestIPv6IfAddrRoute, cls).tearDownClass()
991
992     def setUp(self):
993         super(TestIPv6IfAddrRoute, self).setUp()
994
995         # create 1 pg interface
996         self.create_pg_interfaces(range(1))
997
998         for i in self.pg_interfaces:
999             i.admin_up()
1000             i.config_ip6()
1001             i.resolve_ndp()
1002
1003     def tearDown(self):
1004         super(TestIPv6IfAddrRoute, self).tearDown()
1005         for i in self.pg_interfaces:
1006             i.unconfig_ip6()
1007             i.admin_down()
1008
1009     def test_ipv6_ifaddrs_same_prefix(self):
1010         """ IPv6 Interface Addresses Same Prefix test
1011
1012         Test scenario:
1013
1014             - Verify no route in FIB for prefix 2001:10::/64
1015             - Configure IPv4 address 2001:10::10/64  on an interface
1016             - Verify route in FIB for prefix 2001:10::/64
1017             - Configure IPv4 address 2001:10::20/64 on an interface
1018             - Delete 2001:10::10/64 from interface
1019             - Verify route in FIB for prefix 2001:10::/64
1020             - Delete 2001:10::20/64 from interface
1021             - Verify no route in FIB for prefix 2001:10::/64
1022         """
1023
1024         addr1 = "2001:10::10"
1025         addr2 = "2001:10::20"
1026
1027         if_addr1 = VppIpInterfaceAddress(self, self.pg0, addr1, 64)
1028         if_addr2 = VppIpInterfaceAddress(self, self.pg0, addr2, 64)
1029         self.assertFalse(if_addr1.query_vpp_config())
1030         self.assertFalse(find_route(self, addr1, 128))
1031         self.assertFalse(find_route(self, addr2, 128))
1032
1033         # configure first address, verify route present
1034         if_addr1.add_vpp_config()
1035         self.assertTrue(if_addr1.query_vpp_config())
1036         self.assertTrue(find_route(self, addr1, 128))
1037         self.assertFalse(find_route(self, addr2, 128))
1038
1039         # configure second address, delete first, verify route not removed
1040         if_addr2.add_vpp_config()
1041         if_addr1.remove_vpp_config()
1042         self.assertFalse(if_addr1.query_vpp_config())
1043         self.assertTrue(if_addr2.query_vpp_config())
1044         self.assertFalse(find_route(self, addr1, 128))
1045         self.assertTrue(find_route(self, addr2, 128))
1046
1047         # delete second address, verify route removed
1048         if_addr2.remove_vpp_config()
1049         self.assertFalse(if_addr1.query_vpp_config())
1050         self.assertFalse(find_route(self, addr1, 128))
1051         self.assertFalse(find_route(self, addr2, 128))
1052
1053
1054 class TestICMPv6Echo(VppTestCase):
1055     """ ICMPv6 Echo Test Case """
1056
1057     @classmethod
1058     def setUpClass(cls):
1059         super(TestICMPv6Echo, cls).setUpClass()
1060
1061     @classmethod
1062     def tearDownClass(cls):
1063         super(TestICMPv6Echo, cls).tearDownClass()
1064
1065     def setUp(self):
1066         super(TestICMPv6Echo, self).setUp()
1067
1068         # create 1 pg interface
1069         self.create_pg_interfaces(range(1))
1070
1071         for i in self.pg_interfaces:
1072             i.admin_up()
1073             i.config_ip6()
1074             i.resolve_ndp()
1075
1076     def tearDown(self):
1077         super(TestICMPv6Echo, self).tearDown()
1078         for i in self.pg_interfaces:
1079             i.unconfig_ip6()
1080             i.admin_down()
1081
1082     def test_icmpv6_echo(self):
1083         """ VPP replies to ICMPv6 Echo Request
1084
1085         Test scenario:
1086
1087             - Receive ICMPv6 Echo Request message on pg0 interface.
1088             - Check outgoing ICMPv6 Echo Reply message on pg0 interface.
1089         """
1090
1091         icmpv6_id = 0xb
1092         icmpv6_seq = 5
1093         icmpv6_data = b'\x0a' * 18
1094         p_echo_request = (Ether(src=self.pg0.remote_mac,
1095                                 dst=self.pg0.local_mac) /
1096                           IPv6(src=self.pg0.remote_ip6,
1097                                dst=self.pg0.local_ip6) /
1098                           ICMPv6EchoRequest(
1099                               id=icmpv6_id,
1100                               seq=icmpv6_seq,
1101                               data=icmpv6_data))
1102
1103         self.pg0.add_stream(p_echo_request)
1104         self.pg_enable_capture(self.pg_interfaces)
1105         self.pg_start()
1106
1107         rx = self.pg0.get_capture(1)
1108         rx = rx[0]
1109         ether = rx[Ether]
1110         ipv6 = rx[IPv6]
1111         icmpv6 = rx[ICMPv6EchoReply]
1112
1113         self.assertEqual(ether.src, self.pg0.local_mac)
1114         self.assertEqual(ether.dst, self.pg0.remote_mac)
1115
1116         self.assertEqual(ipv6.src, self.pg0.local_ip6)
1117         self.assertEqual(ipv6.dst, self.pg0.remote_ip6)
1118
1119         self.assertEqual(
1120             icmp6types[icmpv6.type], "Echo Reply")
1121         self.assertEqual(icmpv6.id, icmpv6_id)
1122         self.assertEqual(icmpv6.seq, icmpv6_seq)
1123         self.assertEqual(icmpv6.data, icmpv6_data)
1124
1125
1126 class TestIPv6RD(TestIPv6ND):
1127     """ IPv6 Router Discovery Test Case """
1128
1129     @classmethod
1130     def setUpClass(cls):
1131         super(TestIPv6RD, cls).setUpClass()
1132
1133     @classmethod
1134     def tearDownClass(cls):
1135         super(TestIPv6RD, cls).tearDownClass()
1136
1137     def setUp(self):
1138         super(TestIPv6RD, self).setUp()
1139
1140         # create 2 pg interfaces
1141         self.create_pg_interfaces(range(2))
1142
1143         self.interfaces = list(self.pg_interfaces)
1144
1145         # setup all interfaces
1146         for i in self.interfaces:
1147             i.admin_up()
1148             i.config_ip6()
1149
1150     def tearDown(self):
1151         for i in self.interfaces:
1152             i.unconfig_ip6()
1153             i.admin_down()
1154         super(TestIPv6RD, self).tearDown()
1155
1156     def test_rd_send_router_solicitation(self):
1157         """ Verify router solicitation packets """
1158
1159         count = 2
1160         self.pg_enable_capture(self.pg_interfaces)
1161         self.pg_start()
1162         self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index,
1163                                                  mrc=count)
1164         rx_list = self.pg1.get_capture(count, timeout=3)
1165         self.assertEqual(len(rx_list), count)
1166         for packet in rx_list:
1167             self.assertEqual(packet.haslayer(IPv6), 1)
1168             self.assertEqual(packet[IPv6].haslayer(
1169                 ICMPv6ND_RS), 1)
1170             dst = ip6_normalize(packet[IPv6].dst)
1171             dst2 = ip6_normalize("ff02::2")
1172             self.assert_equal(dst, dst2)
1173             src = ip6_normalize(packet[IPv6].src)
1174             src2 = ip6_normalize(self.pg1.local_ip6_ll)
1175             self.assert_equal(src, src2)
1176             self.assertTrue(
1177                 bool(packet[ICMPv6ND_RS].haslayer(
1178                     ICMPv6NDOptSrcLLAddr)))
1179             self.assert_equal(
1180                 packet[ICMPv6NDOptSrcLLAddr].lladdr,
1181                 self.pg1.local_mac)
1182
1183     def verify_prefix_info(self, reported_prefix, prefix_option):
1184         prefix = IPv6Network(
1185             text_type(prefix_option.getfieldval("prefix") +
1186                       "/" +
1187                       text_type(prefix_option.getfieldval("prefixlen"))),
1188             strict=False)
1189         self.assert_equal(reported_prefix.prefix.network_address,
1190                           prefix.network_address)
1191         L = prefix_option.getfieldval("L")
1192         A = prefix_option.getfieldval("A")
1193         option_flags = (L << 7) | (A << 6)
1194         self.assert_equal(reported_prefix.flags, option_flags)
1195         self.assert_equal(reported_prefix.valid_time,
1196                           prefix_option.getfieldval("validlifetime"))
1197         self.assert_equal(reported_prefix.preferred_time,
1198                           prefix_option.getfieldval("preferredlifetime"))
1199
1200     def test_rd_receive_router_advertisement(self):
1201         """ Verify events triggered by received RA packets """
1202
1203         self.vapi.want_ip6_ra_events(enable=1)
1204
1205         prefix_info_1 = ICMPv6NDOptPrefixInfo(
1206             prefix="1::2",
1207             prefixlen=50,
1208             validlifetime=200,
1209             preferredlifetime=500,
1210             L=1,
1211             A=1,
1212         )
1213
1214         prefix_info_2 = ICMPv6NDOptPrefixInfo(
1215             prefix="7::4",
1216             prefixlen=20,
1217             validlifetime=70,
1218             preferredlifetime=1000,
1219             L=1,
1220             A=0,
1221         )
1222
1223         p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
1224              IPv6(dst=self.pg1.local_ip6_ll,
1225                   src=mk_ll_addr(self.pg1.remote_mac)) /
1226              ICMPv6ND_RA() /
1227              prefix_info_1 /
1228              prefix_info_2)
1229         self.pg1.add_stream([p])
1230         self.pg_start()
1231
1232         ev = self.vapi.wait_for_event(10, "ip6_ra_event")
1233
1234         self.assert_equal(ev.current_hop_limit, 0)
1235         self.assert_equal(ev.flags, 8)
1236         self.assert_equal(ev.router_lifetime_in_sec, 1800)
1237         self.assert_equal(ev.neighbor_reachable_time_in_msec, 0)
1238         self.assert_equal(
1239             ev.time_in_msec_between_retransmitted_neighbor_solicitations, 0)
1240
1241         self.assert_equal(ev.n_prefixes, 2)
1242
1243         self.verify_prefix_info(ev.prefixes[0], prefix_info_1)
1244         self.verify_prefix_info(ev.prefixes[1], prefix_info_2)
1245
1246
1247 class TestIPv6RDControlPlane(TestIPv6ND):
1248     """ IPv6 Router Discovery Control Plane Test Case """
1249
1250     @classmethod
1251     def setUpClass(cls):
1252         super(TestIPv6RDControlPlane, cls).setUpClass()
1253
1254     @classmethod
1255     def tearDownClass(cls):
1256         super(TestIPv6RDControlPlane, cls).tearDownClass()
1257
1258     def setUp(self):
1259         super(TestIPv6RDControlPlane, self).setUp()
1260
1261         # create 1 pg interface
1262         self.create_pg_interfaces(range(1))
1263
1264         self.interfaces = list(self.pg_interfaces)
1265
1266         # setup all interfaces
1267         for i in self.interfaces:
1268             i.admin_up()
1269             i.config_ip6()
1270
1271     def tearDown(self):
1272         super(TestIPv6RDControlPlane, self).tearDown()
1273
1274     @staticmethod
1275     def create_ra_packet(pg, routerlifetime=None):
1276         src_ip = pg.remote_ip6_ll
1277         dst_ip = pg.local_ip6
1278         if routerlifetime is not None:
1279             ra = ICMPv6ND_RA(routerlifetime=routerlifetime)
1280         else:
1281             ra = ICMPv6ND_RA()
1282         p = (Ether(dst=pg.local_mac, src=pg.remote_mac) /
1283              IPv6(dst=dst_ip, src=src_ip) / ra)
1284         return p
1285
1286     @staticmethod
1287     def get_default_routes(fib):
1288         list = []
1289         for entry in fib:
1290             if entry.route.prefix.prefixlen == 0:
1291                 for path in entry.route.paths:
1292                     if path.sw_if_index != 0xFFFFFFFF:
1293                         defaut_route = {}
1294                         defaut_route['sw_if_index'] = path.sw_if_index
1295                         defaut_route['next_hop'] = path.nh.address.ip6
1296                         list.append(defaut_route)
1297         return list
1298
1299     @staticmethod
1300     def get_interface_addresses(fib, pg):
1301         list = []
1302         for entry in fib:
1303             if entry.route.prefix.prefixlen == 128:
1304                 path = entry.route.paths[0]
1305                 if path.sw_if_index == pg.sw_if_index:
1306                     list.append(str(entry.route.prefix.network_address))
1307         return list
1308
1309     def wait_for_no_default_route(self, n_tries=50, s_time=1):
1310         while (n_tries):
1311             fib = self.vapi.ip_route_dump(0, True)
1312             default_routes = self.get_default_routes(fib)
1313             if 0 == len(default_routes):
1314                 return True
1315             n_tries = n_tries - 1
1316             self.sleep(s_time)
1317
1318         return False
1319
1320     def test_all(self):
1321         """ Test handling of SLAAC addresses and default routes """
1322
1323         fib = self.vapi.ip_route_dump(0, True)
1324         default_routes = self.get_default_routes(fib)
1325         initial_addresses = set(self.get_interface_addresses(fib, self.pg0))
1326         self.assertEqual(default_routes, [])
1327         router_address = IPv6Address(text_type(self.pg0.remote_ip6_ll))
1328
1329         self.vapi.ip6_nd_address_autoconfig(self.pg0.sw_if_index, 1, 1)
1330
1331         self.sleep(0.1)
1332
1333         # send RA
1334         packet = (self.create_ra_packet(
1335             self.pg0) / ICMPv6NDOptPrefixInfo(
1336             prefix="1::",
1337             prefixlen=64,
1338             validlifetime=2,
1339             preferredlifetime=2,
1340             L=1,
1341             A=1,
1342         ) / ICMPv6NDOptPrefixInfo(
1343             prefix="7::",
1344             prefixlen=20,
1345             validlifetime=1500,
1346             preferredlifetime=1000,
1347             L=1,
1348             A=0,
1349         ))
1350         self.pg0.add_stream([packet])
1351         self.pg_start()
1352
1353         self.sleep_on_vpp_time(0.1)
1354
1355         fib = self.vapi.ip_route_dump(0, True)
1356
1357         # check FIB for new address
1358         addresses = set(self.get_interface_addresses(fib, self.pg0))
1359         new_addresses = addresses.difference(initial_addresses)
1360         self.assertEqual(len(new_addresses), 1)
1361         prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)),
1362                              strict=False)
1363         self.assertEqual(prefix, IPv6Network(text_type('1::/20')))
1364
1365         # check FIB for new default route
1366         default_routes = self.get_default_routes(fib)
1367         self.assertEqual(len(default_routes), 1)
1368         dr = default_routes[0]
1369         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1370         self.assertEqual(dr['next_hop'], router_address)
1371
1372         # send RA to delete default route
1373         packet = self.create_ra_packet(self.pg0, routerlifetime=0)
1374         self.pg0.add_stream([packet])
1375         self.pg_start()
1376
1377         self.sleep_on_vpp_time(0.1)
1378
1379         # check that default route is deleted
1380         fib = self.vapi.ip_route_dump(0, True)
1381         default_routes = self.get_default_routes(fib)
1382         self.assertEqual(len(default_routes), 0)
1383
1384         self.sleep_on_vpp_time(0.1)
1385
1386         # send RA
1387         packet = self.create_ra_packet(self.pg0)
1388         self.pg0.add_stream([packet])
1389         self.pg_start()
1390
1391         self.sleep_on_vpp_time(0.1)
1392
1393         # check FIB for new default route
1394         fib = self.vapi.ip_route_dump(0, True)
1395         default_routes = self.get_default_routes(fib)
1396         self.assertEqual(len(default_routes), 1)
1397         dr = default_routes[0]
1398         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1399         self.assertEqual(dr['next_hop'], router_address)
1400
1401         # send RA, updating router lifetime to 1s
1402         packet = self.create_ra_packet(self.pg0, 1)
1403         self.pg0.add_stream([packet])
1404         self.pg_start()
1405
1406         self.sleep_on_vpp_time(0.1)
1407
1408         # check that default route still exists
1409         fib = self.vapi.ip_route_dump(0, True)
1410         default_routes = self.get_default_routes(fib)
1411         self.assertEqual(len(default_routes), 1)
1412         dr = default_routes[0]
1413         self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
1414         self.assertEqual(dr['next_hop'], router_address)
1415
1416         self.sleep_on_vpp_time(1)
1417
1418         # check that default route is deleted
1419         self.assertTrue(self.wait_for_no_default_route())
1420
1421         # check FIB still contains the SLAAC address
1422         addresses = set(self.get_interface_addresses(fib, self.pg0))
1423         new_addresses = addresses.difference(initial_addresses)
1424
1425         self.assertEqual(len(new_addresses), 1)
1426         prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)),
1427                              strict=False)
1428         self.assertEqual(prefix, IPv6Network(text_type('1::/20')))
1429
1430         self.sleep_on_vpp_time(1)
1431
1432         # check that SLAAC address is deleted
1433         fib = self.vapi.ip_route_dump(0, True)
1434         addresses = set(self.get_interface_addresses(fib, self.pg0))
1435         new_addresses = addresses.difference(initial_addresses)
1436         self.assertEqual(len(new_addresses), 0)
1437
1438
1439 class IPv6NDProxyTest(TestIPv6ND):
1440     """ IPv6 ND ProxyTest Case """
1441
1442     @classmethod
1443     def setUpClass(cls):
1444         super(IPv6NDProxyTest, cls).setUpClass()
1445
1446     @classmethod
1447     def tearDownClass(cls):
1448         super(IPv6NDProxyTest, cls).tearDownClass()
1449
1450     def setUp(self):
1451         super(IPv6NDProxyTest, self).setUp()
1452
1453         # create 3 pg interfaces
1454         self.create_pg_interfaces(range(3))
1455
1456         # pg0 is the master interface, with the configured subnet
1457         self.pg0.admin_up()
1458         self.pg0.config_ip6()
1459         self.pg0.resolve_ndp()
1460
1461         self.pg1.ip6_enable()
1462         self.pg2.ip6_enable()
1463
1464     def tearDown(self):
1465         super(IPv6NDProxyTest, self).tearDown()
1466
1467     def test_nd_proxy(self):
1468         """ IPv6 Proxy ND """
1469
1470         #
1471         # Generate some hosts in the subnet that we are proxying
1472         #
1473         self.pg0.generate_remote_hosts(8)
1474
1475         nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
1476         d = inet_ntop(AF_INET6, nsma)
1477
1478         #
1479         # Send an NS for one of those remote hosts on one of the proxy links
1480         # expect no response since it's from an address that is not
1481         # on the link that has the prefix configured
1482         #
1483         ns_pg1 = (Ether(dst=in6_getnsmac(nsma), src=self.pg1.remote_mac) /
1484                   IPv6(dst=d,
1485                        src=self.pg0._remote_hosts[2].ip6) /
1486                   ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
1487                   ICMPv6NDOptSrcLLAddr(
1488                       lladdr=self.pg0._remote_hosts[2].mac))
1489
1490         self.send_and_assert_no_replies(self.pg1, ns_pg1, "Off link NS")
1491
1492         #
1493         # Add proxy support for the host
1494         #
1495         self.vapi.ip6nd_proxy_add_del(
1496             is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
1497             sw_if_index=self.pg1.sw_if_index)
1498
1499         #
1500         # try that NS again. this time we expect an NA back
1501         #
1502         self.send_and_expect_na(self.pg1, ns_pg1,
1503                                 "NS to proxy entry",
1504                                 dst_ip=self.pg0._remote_hosts[2].ip6,
1505                                 tgt_ip=self.pg0.local_ip6)
1506
1507         #
1508         # ... and that we have an entry in the ND cache
1509         #
1510         self.assertTrue(find_nbr(self,
1511                                  self.pg1.sw_if_index,
1512                                  self.pg0._remote_hosts[2].ip6))
1513
1514         #
1515         # ... and we can route traffic to it
1516         #
1517         t = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
1518              IPv6(dst=self.pg0._remote_hosts[2].ip6,
1519                   src=self.pg0.remote_ip6) /
1520              inet6.UDP(sport=10000, dport=20000) /
1521              Raw(b'\xa5' * 100))
1522
1523         self.pg0.add_stream(t)
1524         self.pg_enable_capture(self.pg_interfaces)
1525         self.pg_start()
1526         rx = self.pg1.get_capture(1)
1527         rx = rx[0]
1528
1529         self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
1530         self.assertEqual(rx[Ether].src, self.pg1.local_mac)
1531
1532         self.assertEqual(rx[IPv6].src,
1533                          t[IPv6].src)
1534         self.assertEqual(rx[IPv6].dst,
1535                          t[IPv6].dst)
1536
1537         #
1538         # Test we proxy for the host on the main interface
1539         #
1540         ns_pg0 = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
1541                   IPv6(dst=d, src=self.pg0.remote_ip6) /
1542                   ICMPv6ND_NS(
1543                       tgt=self.pg0._remote_hosts[2].ip6) /
1544                   ICMPv6NDOptSrcLLAddr(
1545                       lladdr=self.pg0.remote_mac))
1546
1547         self.send_and_expect_na(self.pg0, ns_pg0,
1548                                 "NS to proxy entry on main",
1549                                 tgt_ip=self.pg0._remote_hosts[2].ip6,
1550                                 dst_ip=self.pg0.remote_ip6)
1551
1552         #
1553         # Setup and resolve proxy for another host on another interface
1554         #
1555         ns_pg2 = (Ether(dst=in6_getnsmac(nsma), src=self.pg2.remote_mac) /
1556                   IPv6(dst=d,
1557                        src=self.pg0._remote_hosts[3].ip6) /
1558                   ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
1559                   ICMPv6NDOptSrcLLAddr(
1560                       lladdr=self.pg0._remote_hosts[2].mac))
1561
1562         self.vapi.ip6nd_proxy_add_del(
1563             is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
1564             sw_if_index=self.pg2.sw_if_index)
1565
1566         self.send_and_expect_na(self.pg2, ns_pg2,
1567                                 "NS to proxy entry other interface",
1568                                 dst_ip=self.pg0._remote_hosts[3].ip6,
1569                                 tgt_ip=self.pg0.local_ip6)
1570
1571         self.assertTrue(find_nbr(self,
1572                                  self.pg2.sw_if_index,
1573                                  self.pg0._remote_hosts[3].ip6))
1574
1575         #
1576         # hosts can communicate. pg2->pg1
1577         #
1578         t2 = (Ether(dst=self.pg2.local_mac,
1579                     src=self.pg0.remote_hosts[3].mac) /
1580               IPv6(dst=self.pg0._remote_hosts[2].ip6,
1581                    src=self.pg0._remote_hosts[3].ip6) /
1582               inet6.UDP(sport=10000, dport=20000) /
1583               Raw(b'\xa5' * 100))
1584
1585         self.pg2.add_stream(t2)
1586         self.pg_enable_capture(self.pg_interfaces)
1587         self.pg_start()
1588         rx = self.pg1.get_capture(1)
1589         rx = rx[0]
1590
1591         self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
1592         self.assertEqual(rx[Ether].src, self.pg1.local_mac)
1593
1594         self.assertEqual(rx[IPv6].src,
1595                          t2[IPv6].src)
1596         self.assertEqual(rx[IPv6].dst,
1597                          t2[IPv6].dst)
1598
1599         #
1600         # remove the proxy configs
1601         #
1602         self.vapi.ip6nd_proxy_add_del(
1603             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
1604             sw_if_index=self.pg1.sw_if_index, is_add=0)
1605         self.vapi.ip6nd_proxy_add_del(
1606             ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
1607             sw_if_index=self.pg2.sw_if_index, is_add=0)
1608
1609         self.assertFalse(find_nbr(self,
1610                                   self.pg2.sw_if_index,
1611                                   self.pg0._remote_hosts[3].ip6))
1612         self.assertFalse(find_nbr(self,
1613                                   self.pg1.sw_if_index,
1614                                   self.pg0._remote_hosts[2].ip6))
1615
1616         #
1617         # no longer proxy-ing...
1618         #
1619         self.send_and_assert_no_replies(self.pg0, ns_pg0, "Proxy unconfigured")
1620         self.send_and_assert_no_replies(self.pg1, ns_pg1, "Proxy unconfigured")
1621         self.send_and_assert_no_replies(self.pg2, ns_pg2, "Proxy unconfigured")
1622
1623         #
1624         # no longer forwarding. traffic generates NS out of the glean/main
1625         # interface
1626         #
1627         self.pg2.add_stream(t2)
1628         self.pg_enable_capture(self.pg_interfaces)
1629         self.pg_start()
1630
1631         rx = self.pg0.get_capture(1)
1632
1633         self.assertTrue(rx[0].haslayer(ICMPv6ND_NS))
1634
1635
1636 class TestIPNull(VppTestCase):
1637     """ IPv6 routes via NULL """
1638
1639     @classmethod
1640     def setUpClass(cls):
1641         super(TestIPNull, cls).setUpClass()
1642
1643     @classmethod
1644     def tearDownClass(cls):
1645         super(TestIPNull, cls).tearDownClass()
1646
1647     def setUp(self):
1648         super(TestIPNull, self).setUp()
1649
1650         # create 2 pg interfaces
1651         self.create_pg_interfaces(range(1))
1652
1653         for i in self.pg_interfaces:
1654             i.admin_up()
1655             i.config_ip6()
1656             i.resolve_ndp()
1657
1658     def tearDown(self):
1659         super(TestIPNull, self).tearDown()
1660         for i in self.pg_interfaces:
1661             i.unconfig_ip6()
1662             i.admin_down()
1663
1664     def test_ip_null(self):
1665         """ IP NULL route """
1666
1667         p = (Ether(src=self.pg0.remote_mac,
1668                    dst=self.pg0.local_mac) /
1669              IPv6(src=self.pg0.remote_ip6, dst="2001::1") /
1670              inet6.UDP(sport=1234, dport=1234) /
1671              Raw(b'\xa5' * 100))
1672
1673         #
1674         # A route via IP NULL that will reply with ICMP unreachables
1675         #
1676         ip_unreach = VppIpRoute(
1677             self, "2001::", 64,
1678             [VppRoutePath("::", 0xffffffff,
1679                           type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH)])
1680         ip_unreach.add_vpp_config()
1681
1682         self.pg0.add_stream(p)
1683         self.pg_enable_capture(self.pg_interfaces)
1684         self.pg_start()
1685
1686         rx = self.pg0.get_capture(1)
1687         rx = rx[0]
1688         icmp = rx[ICMPv6DestUnreach]
1689
1690         # 0 = "No route to destination"
1691         self.assertEqual(icmp.code, 0)
1692
1693         # ICMP is rate limited. pause a bit
1694         self.sleep(1)
1695
1696         #
1697         # A route via IP NULL that will reply with ICMP prohibited
1698         #
1699         ip_prohibit = VppIpRoute(
1700             self, "2001::1", 128,
1701             [VppRoutePath("::", 0xffffffff,
1702                           type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT)])
1703         ip_prohibit.add_vpp_config()
1704
1705         self.pg0.add_stream(p)
1706         self.pg_enable_capture(self.pg_interfaces)
1707         self.pg_start()
1708
1709         rx = self.pg0.get_capture(1)
1710         rx = rx[0]
1711         icmp = rx[ICMPv6DestUnreach]
1712
1713         # 1 = "Communication with destination administratively prohibited"
1714         self.assertEqual(icmp.code, 1)
1715
1716
1717 class TestIPDisabled(VppTestCase):
1718     """ IPv6 disabled """
1719
1720     @classmethod
1721     def setUpClass(cls):
1722         super(TestIPDisabled, cls).setUpClass()
1723
1724     @classmethod
1725     def tearDownClass(cls):
1726         super(TestIPDisabled, cls).tearDownClass()
1727
1728     def setUp(self):
1729         super(TestIPDisabled, self).setUp()
1730
1731         # create 2 pg interfaces
1732         self.create_pg_interfaces(range(2))
1733
1734         # PG0 is IP enabled
1735         self.pg0.admin_up()
1736         self.pg0.config_ip6()
1737         self.pg0.resolve_ndp()
1738
1739         # PG 1 is not IP enabled
1740         self.pg1.admin_up()
1741
1742     def tearDown(self):
1743         super(TestIPDisabled, self).tearDown()
1744         for i in self.pg_interfaces:
1745             i.unconfig_ip4()
1746             i.admin_down()
1747
1748     def test_ip_disabled(self):
1749         """ IP Disabled """
1750
1751         #
1752         # An (S,G).
1753         # one accepting interface, pg0, 2 forwarding interfaces
1754         #
1755         route_ff_01 = VppIpMRoute(
1756             self,
1757             "::",
1758             "ffef::1", 128,
1759             MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
1760             [VppMRoutePath(self.pg1.sw_if_index,
1761                            MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT),
1762              VppMRoutePath(self.pg0.sw_if_index,
1763                            MRouteItfFlags.MFIB_ITF_FLAG_FORWARD)])
1764         route_ff_01.add_vpp_config()
1765
1766         pu = (Ether(src=self.pg1.remote_mac,
1767                     dst=self.pg1.local_mac) /
1768               IPv6(src="2001::1", dst=self.pg0.remote_ip6) /
1769               inet6.UDP(sport=1234, dport=1234) /
1770               Raw(b'\xa5' * 100))
1771         pm = (Ether(src=self.pg1.remote_mac,
1772                     dst=self.pg1.local_mac) /
1773               IPv6(src="2001::1", dst="ffef::1") /
1774               inet6.UDP(sport=1234, dport=1234) /
1775               Raw(b'\xa5' * 100))
1776
1777         #
1778         # PG1 does not forward IP traffic
1779         #
1780         self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled")
1781         self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled")
1782
1783         #
1784         # IP enable PG1
1785         #
1786         self.pg1.config_ip6()
1787
1788         #
1789         # Now we get packets through
1790         #
1791         self.pg1.add_stream(pu)
1792         self.pg_enable_capture(self.pg_interfaces)
1793         self.pg_start()
1794         rx = self.pg0.get_capture(1)
1795
1796         self.pg1.add_stream(pm)
1797         self.pg_enable_capture(self.pg_interfaces)
1798         self.pg_start()
1799         rx = self.pg0.get_capture(1)
1800
1801         #
1802         # Disable PG1
1803         #
1804         self.pg1.unconfig_ip6()
1805
1806         #
1807         # PG1 does not forward IP traffic
1808         #
1809         self.send_and_assert_no_replies(self.pg1, pu, "IPv6 disabled")
1810         self.send_and_assert_no_replies(self.pg1, pm, "IPv6 disabled")
1811
1812
1813 class TestIP6LoadBalance(VppTestCase):
1814     """ IPv6 Load-Balancing """
1815
1816     @classmethod
1817     def setUpClass(cls):
1818         super(TestIP6LoadBalance, cls).setUpClass()
1819
1820     @classmethod
1821     def tearDownClass(cls):
1822         super(TestIP6LoadBalance, cls).tearDownClass()
1823
1824     def setUp(self):
1825         super(TestIP6LoadBalance, self).setUp()
1826
1827         self.create_pg_interfaces(range(5))
1828
1829         mpls_tbl = VppMplsTable(self, 0)
1830         mpls_tbl.add_vpp_config()
1831
1832         for i in self.pg_interfaces:
1833             i.admin_up()
1834             i.config_ip6()
1835             i.resolve_ndp()
1836             i.enable_mpls()
1837
1838     def tearDown(self):
1839         for i in self.pg_interfaces:
1840             i.unconfig_ip6()
1841             i.admin_down()
1842             i.disable_mpls()
1843         super(TestIP6LoadBalance, self).tearDown()
1844
1845     def pg_send(self, input, pkts):
1846         self.vapi.cli("clear trace")
1847         input.add_stream(pkts)
1848         self.pg_enable_capture(self.pg_interfaces)
1849         self.pg_start()
1850
1851     def send_and_expect_load_balancing(self, input, pkts, outputs):
1852         self.pg_send(input, pkts)
1853         for oo in outputs:
1854             rx = oo._get_capture(1)
1855             self.assertNotEqual(0, len(rx))
1856
1857     def send_and_expect_one_itf(self, input, pkts, itf):
1858         self.pg_send(input, pkts)
1859         rx = itf.get_capture(len(pkts))
1860
1861     def test_ip6_load_balance(self):
1862         """ IPv6 Load-Balancing """
1863
1864         #
1865         # An array of packets that differ only in the destination port
1866         #  - IP only
1867         #  - MPLS EOS
1868         #  - MPLS non-EOS
1869         #  - MPLS non-EOS with an entropy label
1870         #
1871         port_ip_pkts = []
1872         port_mpls_pkts = []
1873         port_mpls_neos_pkts = []
1874         port_ent_pkts = []
1875
1876         #
1877         # An array of packets that differ only in the source address
1878         #
1879         src_ip_pkts = []
1880         src_mpls_pkts = []
1881
1882         for ii in range(NUM_PKTS):
1883             port_ip_hdr = (
1884                 IPv6(dst="3000::1", src="3000:1::1") /
1885                 inet6.UDP(sport=1234, dport=1234 + ii) /
1886                 Raw(b'\xa5' * 100))
1887             port_ip_pkts.append((Ether(src=self.pg0.remote_mac,
1888                                        dst=self.pg0.local_mac) /
1889                                  port_ip_hdr))
1890             port_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
1891                                          dst=self.pg0.local_mac) /
1892                                    MPLS(label=66, ttl=2) /
1893                                    port_ip_hdr))
1894             port_mpls_neos_pkts.append((Ether(src=self.pg0.remote_mac,
1895                                               dst=self.pg0.local_mac) /
1896                                         MPLS(label=67, ttl=2) /
1897                                         MPLS(label=77, ttl=2) /
1898                                         port_ip_hdr))
1899             port_ent_pkts.append((Ether(src=self.pg0.remote_mac,
1900                                         dst=self.pg0.local_mac) /
1901                                   MPLS(label=67, ttl=2) /
1902                                   MPLS(label=14, ttl=2) /
1903                                   MPLS(label=999, ttl=2) /
1904                                   port_ip_hdr))
1905             src_ip_hdr = (
1906                 IPv6(dst="3000::1", src="3000:1::%d" % ii) /
1907                 inet6.UDP(sport=1234, dport=1234) /
1908                 Raw(b'\xa5' * 100))
1909             src_ip_pkts.append((Ether(src=self.pg0.remote_mac,
1910                                       dst=self.pg0.local_mac) /
1911                                 src_ip_hdr))
1912             src_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
1913                                         dst=self.pg0.local_mac) /
1914                                   MPLS(label=66, ttl=2) /
1915                                   src_ip_hdr))
1916
1917         #
1918         # A route for the IP packets
1919         #
1920         route_3000_1 = VppIpRoute(self, "3000::1", 128,
1921                                   [VppRoutePath(self.pg1.remote_ip6,
1922                                                 self.pg1.sw_if_index),
1923                                    VppRoutePath(self.pg2.remote_ip6,
1924                                                 self.pg2.sw_if_index)])
1925         route_3000_1.add_vpp_config()
1926
1927         #
1928         # a local-label for the EOS packets
1929         #
1930         binding = VppMplsIpBind(self, 66, "3000::1", 128, is_ip6=1)
1931         binding.add_vpp_config()
1932
1933         #
1934         # An MPLS route for the non-EOS packets
1935         #
1936         route_67 = VppMplsRoute(self, 67, 0,
1937                                 [VppRoutePath(self.pg1.remote_ip6,
1938                                               self.pg1.sw_if_index,
1939                                               labels=[67]),
1940                                  VppRoutePath(self.pg2.remote_ip6,
1941                                               self.pg2.sw_if_index,
1942                                               labels=[67])])
1943         route_67.add_vpp_config()
1944
1945         #
1946         # inject the packet on pg0 - expect load-balancing across the 2 paths
1947         #  - since the default hash config is to use IP src,dst and port
1948         #    src,dst
1949         # We are not going to ensure equal amounts of packets across each link,
1950         # since the hash algorithm is statistical and therefore this can never
1951         # be guaranteed. But with 64 different packets we do expect some
1952         # balancing. So instead just ensure there is traffic on each link.
1953         #
1954         self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
1955                                             [self.pg1, self.pg2])
1956         self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
1957                                             [self.pg1, self.pg2])
1958         self.send_and_expect_load_balancing(self.pg0, port_mpls_pkts,
1959                                             [self.pg1, self.pg2])
1960         self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
1961                                             [self.pg1, self.pg2])
1962         self.send_and_expect_load_balancing(self.pg0, port_mpls_neos_pkts,
1963                                             [self.pg1, self.pg2])
1964
1965         #
1966         # The packets with Entropy label in should not load-balance,
1967         # since the Entropy value is fixed.
1968         #
1969         self.send_and_expect_one_itf(self.pg0, port_ent_pkts, self.pg1)
1970
1971         #
1972         # change the flow hash config so it's only IP src,dst
1973         #  - now only the stream with differing source address will
1974         #    load-balance
1975         #
1976         self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, sport=0, dport=0,
1977                                    is_ipv6=1)
1978
1979         self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
1980                                             [self.pg1, self.pg2])
1981         self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
1982                                             [self.pg1, self.pg2])
1983         self.send_and_expect_one_itf(self.pg0, port_ip_pkts, self.pg2)
1984
1985         #
1986         # change the flow hash config back to defaults
1987         #
1988         self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, sport=1, dport=1,
1989                                    is_ipv6=1)
1990
1991         #
1992         # Recursive prefixes
1993         #  - testing that 2 stages of load-balancing occurs and there is no
1994         #    polarisation (i.e. only 2 of 4 paths are used)
1995         #
1996         port_pkts = []
1997         src_pkts = []
1998
1999         for ii in range(257):
2000             port_pkts.append((Ether(src=self.pg0.remote_mac,
2001                                     dst=self.pg0.local_mac) /
2002                               IPv6(dst="4000::1",
2003                                    src="4000:1::1") /
2004                               inet6.UDP(sport=1234,
2005                                         dport=1234 + ii) /
2006                               Raw(b'\xa5' * 100)))
2007             src_pkts.append((Ether(src=self.pg0.remote_mac,
2008                                    dst=self.pg0.local_mac) /
2009                              IPv6(dst="4000::1",
2010                                   src="4000:1::%d" % ii) /
2011                              inet6.UDP(sport=1234, dport=1234) /
2012                              Raw(b'\xa5' * 100)))
2013
2014         route_3000_2 = VppIpRoute(self, "3000::2", 128,
2015                                   [VppRoutePath(self.pg3.remote_ip6,
2016                                                 self.pg3.sw_if_index),
2017                                    VppRoutePath(self.pg4.remote_ip6,
2018                                                 self.pg4.sw_if_index)])
2019         route_3000_2.add_vpp_config()
2020
2021         route_4000_1 = VppIpRoute(self, "4000::1", 128,
2022                                   [VppRoutePath("3000::1",
2023                                                 0xffffffff),
2024                                    VppRoutePath("3000::2",
2025                                                 0xffffffff)])
2026         route_4000_1.add_vpp_config()
2027
2028         #
2029         # inject the packet on pg0 - expect load-balancing across all 4 paths
2030         #
2031         self.vapi.cli("clear trace")
2032         self.send_and_expect_load_balancing(self.pg0, port_pkts,
2033                                             [self.pg1, self.pg2,
2034                                              self.pg3, self.pg4])
2035         self.send_and_expect_load_balancing(self.pg0, src_pkts,
2036                                             [self.pg1, self.pg2,
2037                                              self.pg3, self.pg4])
2038
2039         #
2040         # Recursive prefixes
2041         #  - testing that 2 stages of load-balancing no choices
2042         #
2043         port_pkts = []
2044
2045         for ii in range(257):
2046             port_pkts.append((Ether(src=self.pg0.remote_mac,
2047                                     dst=self.pg0.local_mac) /
2048                               IPv6(dst="6000::1",
2049                                    src="6000:1::1") /
2050                               inet6.UDP(sport=1234,
2051                                         dport=1234 + ii) /
2052                               Raw(b'\xa5' * 100)))
2053
2054         route_5000_2 = VppIpRoute(self, "5000::2", 128,
2055                                   [VppRoutePath(self.pg3.remote_ip6,
2056                                                 self.pg3.sw_if_index)])
2057         route_5000_2.add_vpp_config()
2058
2059         route_6000_1 = VppIpRoute(self, "6000::1", 128,
2060                                   [VppRoutePath("5000::2",
2061                                                 0xffffffff)])
2062         route_6000_1.add_vpp_config()
2063
2064         #
2065         # inject the packet on pg0 - expect load-balancing across all 4 paths
2066         #
2067         self.vapi.cli("clear trace")
2068         self.send_and_expect_one_itf(self.pg0, port_pkts, self.pg3)
2069
2070
2071 class TestIP6Punt(VppTestCase):
2072     """ IPv6 Punt Police/Redirect """
2073
2074     @classmethod
2075     def setUpClass(cls):
2076         super(TestIP6Punt, cls).setUpClass()
2077
2078     @classmethod
2079     def tearDownClass(cls):
2080         super(TestIP6Punt, cls).tearDownClass()
2081
2082     def setUp(self):
2083         super(TestIP6Punt, self).setUp()
2084
2085         self.create_pg_interfaces(range(4))
2086
2087         for i in self.pg_interfaces:
2088             i.admin_up()
2089             i.config_ip6()
2090             i.resolve_ndp()
2091
2092     def tearDown(self):
2093         super(TestIP6Punt, self).tearDown()
2094         for i in self.pg_interfaces:
2095             i.unconfig_ip6()
2096             i.admin_down()
2097
2098     def test_ip_punt(self):
2099         """ IP6 punt police and redirect """
2100
2101         p = (Ether(src=self.pg0.remote_mac,
2102                    dst=self.pg0.local_mac) /
2103              IPv6(src=self.pg0.remote_ip6,
2104                   dst=self.pg0.local_ip6) /
2105              inet6.TCP(sport=1234, dport=1234) /
2106              Raw(b'\xa5' * 100))
2107
2108         pkts = p * 1025
2109
2110         #
2111         # Configure a punt redirect via pg1.
2112         #
2113         nh_addr = self.pg1.remote_ip6
2114         self.vapi.ip_punt_redirect(self.pg0.sw_if_index,
2115                                    self.pg1.sw_if_index,
2116                                    nh_addr)
2117
2118         self.send_and_expect(self.pg0, pkts, self.pg1)
2119
2120         #
2121         # add a policer
2122         #
2123         policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, rate_type=1)
2124         policer.add_vpp_config()
2125         self.vapi.ip_punt_police(policer.policer_index, is_ip6=1)
2126
2127         self.vapi.cli("clear trace")
2128         self.pg0.add_stream(pkts)
2129         self.pg_enable_capture(self.pg_interfaces)
2130         self.pg_start()
2131
2132         #
2133         # the number of packet received should be greater than 0,
2134         # but not equal to the number sent, since some were policed
2135         #
2136         rx = self.pg1._get_capture(1)
2137         self.assertGreater(len(rx), 0)
2138         self.assertLess(len(rx), len(pkts))
2139
2140         #
2141         # remove the policer. back to full rx
2142         #
2143         self.vapi.ip_punt_police(policer.policer_index, is_add=0, is_ip6=1)
2144         policer.remove_vpp_config()
2145         self.send_and_expect(self.pg0, pkts, self.pg1)
2146
2147         #
2148         # remove the redirect. expect full drop.
2149         #
2150         self.vapi.ip_punt_redirect(self.pg0.sw_if_index,
2151                                    self.pg1.sw_if_index,
2152                                    nh_addr,
2153                                    is_add=0)
2154         self.send_and_assert_no_replies(self.pg0, pkts,
2155                                         "IP no punt config")
2156
2157         #
2158         # Add a redirect that is not input port selective
2159         #
2160         self.vapi.ip_punt_redirect(0xffffffff,
2161                                    self.pg1.sw_if_index,
2162                                    nh_addr)
2163         self.send_and_expect(self.pg0, pkts, self.pg1)
2164
2165         self.vapi.ip_punt_redirect(0xffffffff,
2166                                    self.pg1.sw_if_index,
2167                                    nh_addr,
2168                                    is_add=0)
2169
2170     def test_ip_punt_dump(self):
2171         """ IP6 punt redirect dump"""
2172
2173         #
2174         # Configure a punt redirects
2175         #
2176         nh_addr = self.pg3.remote_ip6
2177         self.vapi.ip_punt_redirect(self.pg0.sw_if_index,
2178                                    self.pg3.sw_if_index,
2179                                    nh_addr)
2180         self.vapi.ip_punt_redirect(self.pg1.sw_if_index,
2181                                    self.pg3.sw_if_index,
2182                                    nh_addr)
2183         self.vapi.ip_punt_redirect(self.pg2.sw_if_index,
2184                                    self.pg3.sw_if_index,
2185                                    '0::0')
2186
2187         #
2188         # Dump pg0 punt redirects
2189         #
2190         punts = self.vapi.ip_punt_redirect_dump(self.pg0.sw_if_index,
2191                                                 is_ipv6=1)
2192         for p in punts:
2193             self.assertEqual(p.punt.rx_sw_if_index, self.pg0.sw_if_index)
2194
2195         #
2196         # Dump punt redirects for all interfaces
2197         #
2198         punts = self.vapi.ip_punt_redirect_dump(0xffffffff, is_ipv6=1)
2199         self.assertEqual(len(punts), 3)
2200         for p in punts:
2201             self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index)
2202         self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip6)
2203         self.assertEqual(str(punts[2].punt.nh), '::')
2204
2205
2206 class TestIPDeag(VppTestCase):
2207     """ IPv6 Deaggregate Routes """
2208
2209     @classmethod
2210     def setUpClass(cls):
2211         super(TestIPDeag, cls).setUpClass()
2212
2213     @classmethod
2214     def tearDownClass(cls):
2215         super(TestIPDeag, cls).tearDownClass()
2216
2217     def setUp(self):
2218         super(TestIPDeag, self).setUp()
2219
2220         self.create_pg_interfaces(range(3))
2221
2222         for i in self.pg_interfaces:
2223             i.admin_up()
2224             i.config_ip6()
2225             i.resolve_ndp()
2226
2227     def tearDown(self):
2228         super(TestIPDeag, self).tearDown()
2229         for i in self.pg_interfaces:
2230             i.unconfig_ip6()
2231             i.admin_down()
2232
2233     def test_ip_deag(self):
2234         """ IP Deag Routes """
2235
2236         #
2237         # Create a table to be used for:
2238         #  1 - another destination address lookup
2239         #  2 - a source address lookup
2240         #
2241         table_dst = VppIpTable(self, 1, is_ip6=1)
2242         table_src = VppIpTable(self, 2, is_ip6=1)
2243         table_dst.add_vpp_config()
2244         table_src.add_vpp_config()
2245
2246         #
2247         # Add a route in the default table to point to a deag/
2248         # second lookup in each of these tables
2249         #
2250         route_to_dst = VppIpRoute(self, "1::1", 128,
2251                                   [VppRoutePath("::",
2252                                                 0xffffffff,
2253                                                 nh_table_id=1)])
2254         route_to_src = VppIpRoute(
2255             self, "1::2", 128,
2256             [VppRoutePath("::",
2257                           0xffffffff,
2258                           nh_table_id=2,
2259                           type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP)])
2260
2261         route_to_dst.add_vpp_config()
2262         route_to_src.add_vpp_config()
2263
2264         #
2265         # packets to these destination are dropped, since they'll
2266         # hit the respective default routes in the second table
2267         #
2268         p_dst = (Ether(src=self.pg0.remote_mac,
2269                        dst=self.pg0.local_mac) /
2270                  IPv6(src="5::5", dst="1::1") /
2271                  inet6.TCP(sport=1234, dport=1234) /
2272                  Raw(b'\xa5' * 100))
2273         p_src = (Ether(src=self.pg0.remote_mac,
2274                        dst=self.pg0.local_mac) /
2275                  IPv6(src="2::2", dst="1::2") /
2276                  inet6.TCP(sport=1234, dport=1234) /
2277                  Raw(b'\xa5' * 100))
2278         pkts_dst = p_dst * 257
2279         pkts_src = p_src * 257
2280
2281         self.send_and_assert_no_replies(self.pg0, pkts_dst,
2282                                         "IP in dst table")
2283         self.send_and_assert_no_replies(self.pg0, pkts_src,
2284                                         "IP in src table")
2285
2286         #
2287         # add a route in the dst table to forward via pg1
2288         #
2289         route_in_dst = VppIpRoute(self, "1::1", 128,
2290                                   [VppRoutePath(self.pg1.remote_ip6,
2291                                                 self.pg1.sw_if_index)],
2292                                   table_id=1)
2293         route_in_dst.add_vpp_config()
2294
2295         self.send_and_expect(self.pg0, pkts_dst, self.pg1)
2296
2297         #
2298         # add a route in the src table to forward via pg2
2299         #
2300         route_in_src = VppIpRoute(self, "2::2", 128,
2301                                   [VppRoutePath(self.pg2.remote_ip6,
2302                                                 self.pg2.sw_if_index)],
2303                                   table_id=2)
2304         route_in_src.add_vpp_config()
2305         self.send_and_expect(self.pg0, pkts_src, self.pg2)
2306
2307         #
2308         # loop in the lookup DP
2309         #
2310         route_loop = VppIpRoute(self, "3::3", 128,
2311                                 [VppRoutePath("::",
2312                                               0xffffffff)])
2313         route_loop.add_vpp_config()
2314
2315         p_l = (Ether(src=self.pg0.remote_mac,
2316                      dst=self.pg0.local_mac) /
2317                IPv6(src="3::4", dst="3::3") /
2318                inet6.TCP(sport=1234, dport=1234) /
2319                Raw(b'\xa5' * 100))
2320
2321         self.send_and_assert_no_replies(self.pg0, p_l * 257,
2322                                         "IP lookup loop")
2323
2324
2325 class TestIP6Input(VppTestCase):
2326     """ IPv6 Input Exception Test Cases """
2327
2328     @classmethod
2329     def setUpClass(cls):
2330         super(TestIP6Input, cls).setUpClass()
2331
2332     @classmethod
2333     def tearDownClass(cls):
2334         super(TestIP6Input, cls).tearDownClass()
2335
2336     def setUp(self):
2337         super(TestIP6Input, self).setUp()
2338
2339         self.create_pg_interfaces(range(2))
2340
2341         for i in self.pg_interfaces:
2342             i.admin_up()
2343             i.config_ip6()
2344             i.resolve_ndp()
2345
2346     def tearDown(self):
2347         super(TestIP6Input, self).tearDown()
2348         for i in self.pg_interfaces:
2349             i.unconfig_ip6()
2350             i.admin_down()
2351
2352     def test_ip_input_icmp_reply(self):
2353         """ IP6 Input Exception - Return ICMP (3,0) """
2354         #
2355         # hop limit - ICMP replies
2356         #
2357         p_version = (Ether(src=self.pg0.remote_mac,
2358                            dst=self.pg0.local_mac) /
2359                      IPv6(src=self.pg0.remote_ip6,
2360                           dst=self.pg1.remote_ip6,
2361                           hlim=1) /
2362                      inet6.UDP(sport=1234, dport=1234) /
2363                      Raw(b'\xa5' * 100))
2364
2365         rx = self.send_and_expect(self.pg0, p_version * NUM_PKTS, self.pg0)
2366         rx = rx[0]
2367         icmp = rx[ICMPv6TimeExceeded]
2368
2369         # 0: "hop limit exceeded in transit",
2370         self.assertEqual((icmp.type, icmp.code), (3, 0))
2371
2372     icmpv6_data = '\x0a' * 18
2373     all_0s = "::"
2374     all_1s = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"
2375
2376     @parameterized.expand([
2377         # Name, src, dst, l4proto, msg, timeout
2378         ("src='iface',   dst='iface'", None, None,
2379          inet6.UDP(sport=1234, dport=1234), "funky version", None),
2380         ("src='All 0's', dst='iface'", all_0s, None,
2381          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2382         ("src='iface',   dst='All 0's'", None, all_0s,
2383          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2384         ("src='All 1's', dst='iface'", all_1s, None,
2385          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2386         ("src='iface',   dst='All 1's'", None, all_1s,
2387          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2388         ("src='All 1's', dst='All 1's'", all_1s, all_1s,
2389          ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
2390
2391     ])
2392     def test_ip_input_no_replies(self, name, src, dst, l4, msg, timeout):
2393
2394         self._testMethodDoc = 'IPv6 Input Exception - %s' % name
2395
2396         p_version = (Ether(src=self.pg0.remote_mac,
2397                            dst=self.pg0.local_mac) /
2398                      IPv6(src=src or self.pg0.remote_ip6,
2399                           dst=dst or self.pg1.remote_ip6,
2400                           version=3) /
2401                      l4 /
2402                      Raw(b'\xa5' * 100))
2403
2404         self.send_and_assert_no_replies(self.pg0, p_version * NUM_PKTS,
2405                                         remark=msg or "",
2406                                         timeout=timeout)
2407
2408     def test_hop_by_hop(self):
2409         """ Hop-by-hop header test """
2410
2411         p = (Ether(src=self.pg0.remote_mac,
2412                    dst=self.pg0.local_mac) /
2413              IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
2414              IPv6ExtHdrHopByHop() /
2415              inet6.UDP(sport=1234, dport=1234) /
2416              Raw(b'\xa5' * 100))
2417
2418         self.pg0.add_stream(p)
2419         self.pg_enable_capture(self.pg_interfaces)
2420         self.pg_start()
2421
2422
2423 class TestIPReplace(VppTestCase):
2424     """ IPv6 Table Replace """
2425
2426     @classmethod
2427     def setUpClass(cls):
2428         super(TestIPReplace, cls).setUpClass()
2429
2430     @classmethod
2431     def tearDownClass(cls):
2432         super(TestIPReplace, cls).tearDownClass()
2433
2434     def setUp(self):
2435         super(TestIPReplace, self).setUp()
2436
2437         self.create_pg_interfaces(range(4))
2438
2439         table_id = 1
2440         self.tables = []
2441
2442         for i in self.pg_interfaces:
2443             i.admin_up()
2444             i.config_ip6()
2445             i.resolve_arp()
2446             i.generate_remote_hosts(2)
2447             self.tables.append(VppIpTable(self, table_id,
2448                                           True).add_vpp_config())
2449             table_id += 1
2450
2451     def tearDown(self):
2452         super(TestIPReplace, self).tearDown()
2453         for i in self.pg_interfaces:
2454             i.admin_down()
2455             i.unconfig_ip4()
2456
2457     def test_replace(self):
2458         """ IP Table Replace """
2459
2460         N_ROUTES = 20
2461         links = [self.pg0, self.pg1, self.pg2, self.pg3]
2462         routes = [[], [], [], []]
2463
2464         # the sizes of 'empty' tables
2465         for t in self.tables:
2466             self.assertEqual(len(t.dump()), 2)
2467             self.assertEqual(len(t.mdump()), 5)
2468
2469         # load up the tables with some routes
2470         for ii, t in enumerate(self.tables):
2471             for jj in range(1, N_ROUTES):
2472                 uni = VppIpRoute(
2473                     self, "2001::%d" % jj if jj != 0 else "2001::", 128,
2474                     [VppRoutePath(links[ii].remote_hosts[0].ip6,
2475                                   links[ii].sw_if_index),
2476                      VppRoutePath(links[ii].remote_hosts[1].ip6,
2477                                   links[ii].sw_if_index)],
2478                     table_id=t.table_id).add_vpp_config()
2479                 multi = VppIpMRoute(
2480                     self, "::",
2481                     "ff:2001::%d" % jj, 128,
2482                     MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
2483                     [VppMRoutePath(self.pg0.sw_if_index,
2484                                    MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT,
2485                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
2486                      VppMRoutePath(self.pg1.sw_if_index,
2487                                    MRouteItfFlags.MFIB_ITF_FLAG_FORWARD,
2488                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
2489                      VppMRoutePath(self.pg2.sw_if_index,
2490                                    MRouteItfFlags.MFIB_ITF_FLAG_FORWARD,
2491                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
2492                      VppMRoutePath(self.pg3.sw_if_index,
2493                                    MRouteItfFlags.MFIB_ITF_FLAG_FORWARD,
2494                                    proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)],
2495                     table_id=t.table_id).add_vpp_config()
2496                 routes[ii].append({'uni': uni,
2497                                    'multi': multi})
2498
2499         #
2500         # replace the tables a few times
2501         #
2502         for kk in range(3):
2503             # replace each table
2504             for t in self.tables:
2505                 t.replace_begin()
2506
2507             # all the routes are still there
2508             for ii, t in enumerate(self.tables):
2509                 dump = t.dump()
2510                 mdump = t.mdump()
2511                 for r in routes[ii]:
2512                     self.assertTrue(find_route_in_dump(dump, r['uni'], t))
2513                     self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
2514
2515             # redownload the even numbered routes
2516             for ii, t in enumerate(self.tables):
2517                 for jj in range(0, N_ROUTES, 2):
2518                     routes[ii][jj]['uni'].add_vpp_config()
2519                     routes[ii][jj]['multi'].add_vpp_config()
2520
2521             # signal each table converged
2522             for t in self.tables:
2523                 t.replace_end()
2524
2525             # we should find the even routes, but not the odd
2526             for ii, t in enumerate(self.tables):
2527                 dump = t.dump()
2528                 mdump = t.mdump()
2529                 for jj in range(0, N_ROUTES, 2):
2530                     self.assertTrue(find_route_in_dump(
2531                         dump, routes[ii][jj]['uni'], t))
2532                     self.assertTrue(find_mroute_in_dump(
2533                         mdump, routes[ii][jj]['multi'], t))
2534                 for jj in range(1, N_ROUTES - 1, 2):
2535                     self.assertFalse(find_route_in_dump(
2536                         dump, routes[ii][jj]['uni'], t))
2537                     self.assertFalse(find_mroute_in_dump(
2538                         mdump, routes[ii][jj]['multi'], t))
2539
2540             # reload all the routes
2541             for ii, t in enumerate(self.tables):
2542                 for r in routes[ii]:
2543                     r['uni'].add_vpp_config()
2544                     r['multi'].add_vpp_config()
2545
2546             # all the routes are still there
2547             for ii, t in enumerate(self.tables):
2548                 dump = t.dump()
2549                 mdump = t.mdump()
2550                 for r in routes[ii]:
2551                     self.assertTrue(find_route_in_dump(dump, r['uni'], t))
2552                     self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
2553
2554         #
2555         # finally flush the tables for good measure
2556         #
2557         for t in self.tables:
2558             t.flush()
2559             self.assertEqual(len(t.dump()), 2)
2560             self.assertEqual(len(t.mdump()), 5)
2561
2562
2563 class TestIP6Replace(VppTestCase):
2564     """ IPv4 Interface Address Replace """
2565
2566     @classmethod
2567     def setUpClass(cls):
2568         super(TestIP6Replace, cls).setUpClass()
2569
2570     @classmethod
2571     def tearDownClass(cls):
2572         super(TestIP6Replace, cls).tearDownClass()
2573
2574     def setUp(self):
2575         super(TestIP6Replace, self).setUp()
2576
2577         self.create_pg_interfaces(range(4))
2578
2579         for i in self.pg_interfaces:
2580             i.admin_up()
2581
2582     def tearDown(self):
2583         super(TestIP6Replace, self).tearDown()
2584         for i in self.pg_interfaces:
2585             i.admin_down()
2586
2587     def get_n_pfxs(self, intf):
2588         return len(self.vapi.ip_address_dump(intf.sw_if_index, True))
2589
2590     def test_replace(self):
2591         """ IP interface address replace """
2592
2593         intf_pfxs = [[], [], [], []]
2594
2595         # add prefixes to each of the interfaces
2596         for i in range(len(self.pg_interfaces)):
2597             intf = self.pg_interfaces[i]
2598
2599             # 2001:16:x::1/64
2600             addr = "2001:16:%d::1" % intf.sw_if_index
2601             a = VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2602             intf_pfxs[i].append(a)
2603
2604             # 2001:16:x::2/64 - a different address in the same subnet as above
2605             addr = "2001:16:%d::2" % intf.sw_if_index
2606             a = VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2607             intf_pfxs[i].append(a)
2608
2609             # 2001:15:x::2/64 - a different address and subnet
2610             addr = "2001:15:%d::2" % intf.sw_if_index
2611             a = VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2612             intf_pfxs[i].append(a)
2613
2614         # a dump should n_address in it
2615         for intf in self.pg_interfaces:
2616             self.assertEqual(self.get_n_pfxs(intf), 3)
2617
2618         #
2619         # remove all the address thru a replace
2620         #
2621         self.vapi.sw_interface_address_replace_begin()
2622         self.vapi.sw_interface_address_replace_end()
2623         for intf in self.pg_interfaces:
2624             self.assertEqual(self.get_n_pfxs(intf), 0)
2625
2626         #
2627         # add all the interface addresses back
2628         #
2629         for p in intf_pfxs:
2630             for v in p:
2631                 v.add_vpp_config()
2632         for intf in self.pg_interfaces:
2633             self.assertEqual(self.get_n_pfxs(intf), 3)
2634
2635         #
2636         # replace again, but this time update/re-add the address on the first
2637         # two interfaces
2638         #
2639         self.vapi.sw_interface_address_replace_begin()
2640
2641         for p in intf_pfxs[:2]:
2642             for v in p:
2643                 v.add_vpp_config()
2644
2645         self.vapi.sw_interface_address_replace_end()
2646
2647         # on the first two the address still exist,
2648         # on the other two they do not
2649         for intf in self.pg_interfaces[:2]:
2650             self.assertEqual(self.get_n_pfxs(intf), 3)
2651         for p in intf_pfxs[:2]:
2652             for v in p:
2653                 self.assertTrue(v.query_vpp_config())
2654         for intf in self.pg_interfaces[2:]:
2655             self.assertEqual(self.get_n_pfxs(intf), 0)
2656
2657         #
2658         # add all the interface addresses back on the last two
2659         #
2660         for p in intf_pfxs[2:]:
2661             for v in p:
2662                 v.add_vpp_config()
2663         for intf in self.pg_interfaces:
2664             self.assertEqual(self.get_n_pfxs(intf), 3)
2665
2666         #
2667         # replace again, this time add different prefixes on all the interfaces
2668         #
2669         self.vapi.sw_interface_address_replace_begin()
2670
2671         pfxs = []
2672         for intf in self.pg_interfaces:
2673             # 2001:18:x::1/64
2674             addr = "2001:18:%d::1" % intf.sw_if_index
2675             pfxs.append(VppIpInterfaceAddress(self, intf, addr,
2676                                               64).add_vpp_config())
2677
2678         self.vapi.sw_interface_address_replace_end()
2679
2680         # only .18 should exist on each interface
2681         for intf in self.pg_interfaces:
2682             self.assertEqual(self.get_n_pfxs(intf), 1)
2683         for pfx in pfxs:
2684             self.assertTrue(pfx.query_vpp_config())
2685
2686         #
2687         # remove everything
2688         #
2689         self.vapi.sw_interface_address_replace_begin()
2690         self.vapi.sw_interface_address_replace_end()
2691         for intf in self.pg_interfaces:
2692             self.assertEqual(self.get_n_pfxs(intf), 0)
2693
2694         #
2695         # add prefixes to each interface. post-begin add the prefix from
2696         # interface X onto interface Y. this would normally be an error
2697         # since it would generate a 'duplicate address' warning. but in
2698         # this case, since what is newly downloaded is sane, it's ok
2699         #
2700         for intf in self.pg_interfaces:
2701             # 2001:18:x::1/64
2702             addr = "2001:18:%d::1" % intf.sw_if_index
2703             VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()
2704
2705         self.vapi.sw_interface_address_replace_begin()
2706
2707         pfxs = []
2708         for intf in self.pg_interfaces:
2709             # 2001:18:x::1/64
2710             addr = "2001:18:%d::1" % (intf.sw_if_index + 1)
2711             pfxs.append(VppIpInterfaceAddress(self, intf,
2712                                               addr, 64).add_vpp_config())
2713
2714         self.vapi.sw_interface_address_replace_end()
2715
2716         self.logger.info(self.vapi.cli("sh int addr"))
2717
2718         for intf in self.pg_interfaces:
2719             self.assertEqual(self.get_n_pfxs(intf), 1)
2720         for pfx in pfxs:
2721             self.assertTrue(pfx.query_vpp_config())
2722
2723
2724 if __name__ == '__main__':
2725     unittest.main(testRunner=VppTestRunner)