#!/usr/bin/env python3 import binascii import random import socket import unittest import scapy.compat from scapy.contrib.mpls import MPLS from scapy.layers.inet import IP, UDP, TCP, ICMP, icmptypes, icmpcodes from scapy.layers.l2 import Ether, Dot1Q, ARP from scapy.packet import Raw from six import moves from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from util import ppp from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpMRoute, \ VppMRoutePath, VppMplsIpBind, \ VppMplsTable, VppIpTable, FibPathType, find_route, \ VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump from vpp_ip import VppIpPuntPolicer, VppIpPuntRedirect, VppIpPathMtu from vpp_sub_interface import VppSubInterface, VppDot1QSubint, VppDot1ADSubint from vpp_papi import VppEnum from vpp_neighbor import VppNeighbor from vpp_lo_interface import VppLoInterface from vpp_policer import VppPolicer, PolicerAction NUM_PKTS = 67 class TestIPv4(VppTestCase): """ IPv4 Test Case """ @classmethod def setUpClass(cls): super(TestIPv4, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPv4, cls).tearDownClass() def setUp(self): """ Perform test setup before test case. **Config:** - create 3 pg interfaces - untagged pg0 interface - Dot1Q subinterface on pg1 - Dot1AD subinterface on pg2 - setup interfaces: - put it into UP state - set IPv4 addresses - resolve neighbor address using ARP - configure 200 fib entries :ivar list interfaces: pg interfaces and subinterfaces. :ivar dict flows: IPv4 packet flows in test. """ super(TestIPv4, self).setUp() # create 3 pg interfaces self.create_pg_interfaces(range(3)) # create 2 subinterfaces for pg1 and pg2 self.sub_interfaces = [ VppDot1QSubint(self, self.pg1, 100), VppDot1ADSubint(self, self.pg2, 200, 300, 400)] # packet flows mapping pg0 -> pg1.sub, pg2.sub, etc. self.flows = dict() self.flows[self.pg0] = [self.pg1.sub_if, self.pg2.sub_if] self.flows[self.pg1.sub_if] = [self.pg0, self.pg2.sub_if] self.flows[self.pg2.sub_if] = [self.pg0, self.pg1.sub_if] # packet sizes self.pg_if_packet_sizes = [64, 1500, 9020] self.interfaces = list(self.pg_interfaces) self.interfaces.extend(self.sub_interfaces) # setup all interfaces for i in self.interfaces: i.admin_up() i.config_ip4() i.resolve_arp() # config 2M FIB entries def tearDown(self): """Run standard test teardown and log ``show ip arp``.""" super(TestIPv4, self).tearDown() def show_commands_at_teardown(self): self.logger.info(self.vapi.cli("show ip4 neighbors")) # info(self.vapi.cli("show ip fib")) # many entries def modify_packet(self, src_if, packet_size, pkt): """Add load, set destination IP and extend packet to required packet size for defined interface. :param VppInterface src_if: Interface to create packet for. :param int packet_size: Required packet size. :param Scapy pkt: Packet to be modified. """ dst_if_idx = int(packet_size / 10 % 2) dst_if = self.flows[src_if][dst_if_idx] info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(info) p = pkt/Raw(payload) p[IP].dst = dst_if.remote_ip4 info.data = p.copy() if isinstance(src_if, VppSubInterface): p = src_if.add_dot1_layer(p) self.extend_packet(p, packet_size) return p def create_stream(self, src_if): """Create input packet stream for defined interface. :param VppInterface src_if: Interface to create packet stream for. """ hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0 pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / IP(src=src_if.remote_ip4) / UDP(sport=1234, dport=1234)) pkts = [self.modify_packet(src_if, i, pkt_tmpl) for i in moves.range(self.pg_if_packet_sizes[0], self.pg_if_packet_sizes[1], 10)] pkts_b = [self.modify_packet(src_if, i, pkt_tmpl) for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext, self.pg_if_packet_sizes[2] + hdr_ext, 50)] pkts.extend(pkts_b) return pkts def verify_capture(self, dst_if, capture): """Verify captured input packet stream for defined interface. :param VppInterface dst_if: Interface to verify captured packet stream for. :param list capture: Captured packet stream. """ self.logger.info("Verifying capture on interface %s" % dst_if.name) last_info = dict() for i in self.interfaces: last_info[i.sw_if_index] = None is_sub_if = False dst_sw_if_index = dst_if.sw_if_index if hasattr(dst_if, 'parent'): is_sub_if = True for packet in capture: if is_sub_if: # Check VLAN tags and Ethernet header packet = dst_if.remove_dot1_layer(packet) self.assertTrue(Dot1Q not in packet) try: ip = packet[IP] udp = packet[UDP] payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( "Got packet on port %s: src=%u (id=%u)" % (dst_if.name, payload_info.src, packet_index)) next_info = self.get_next_packet_info_for_interface2( payload_info.src, dst_sw_if_index, last_info[payload_info.src]) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) saved_packet = next_info.data # Check standard fields self.assertEqual(ip.src, saved_packet[IP].src) self.assertEqual(ip.dst, saved_packet[IP].dst) self.assertEqual(udp.sport, saved_packet[UDP].sport) self.assertEqual(udp.dport, saved_packet[UDP].dport) except: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for i in self.interfaces: remaining_packet = self.get_next_packet_info_for_interface2( i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]) self.assertTrue(remaining_packet is None, "Interface %s: Packet expected from interface %s " "didn't arrive" % (dst_if.name, i.name)) def test_fib(self): """ IPv4 FIB test Test scenario: - Create IPv4 stream for pg0 interface - Create IPv4 tagged streams for pg1's and pg2's sub-interface. - Send and verify received packets on each interface. """ pkts = self.create_stream(self.pg0) self.pg0.add_stream(pkts) for i in self.sub_interfaces: pkts = self.create_stream(i) i.parent.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() pkts = self.pg0.get_capture() self.verify_capture(self.pg0, pkts) for i in self.sub_interfaces: pkts = i.parent.get_capture() self.verify_capture(i, pkts) class TestIPv4RouteLookup(VppTestCase): """ IPv4 Route Lookup Test Case """ routes = [] def route_lookup(self, prefix, exact): return self.vapi.api(self.vapi.papi.ip_route_lookup, { 'table_id': 0, 'exact': exact, 'prefix': prefix, }) @classmethod def setUpClass(cls): super(TestIPv4RouteLookup, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPv4RouteLookup, cls).tearDownClass() def setUp(self): super(TestIPv4RouteLookup, self).setUp() drop_nh = VppRoutePath("127.0.0.1", 0xffffffff, type=FibPathType.FIB_PATH_TYPE_DROP) # Add 3 routes r = VppIpRoute(self, "1.1.0.0", 16, [drop_nh]) r.add_vpp_config() self.routes.append(r) r = VppIpRoute(self, "1.1.1.0", 24, [drop_nh]) r.add_vpp_config() self.routes.append(r) r = VppIpRoute(self, "1.1.1.1", 32, [drop_nh]) r.add_vpp_config() self.routes.append(r) def tearDown(self): # Remove the routes we added for r in self.routes: r.remove_vpp_config() super(TestIPv4RouteLookup, self).tearDown() def test_exact_match(self): # Verify we find the host route prefix = "1.1.1.1/32" result = self.route_lookup(prefix, True) assert (prefix == str(result.route.prefix)) # Verify we find a middle prefix route prefix = "1.1.1.0/24" result = self.route_lookup(prefix, True) assert (prefix == str(result.route.prefix)) # Verify we do not find an available LPM. with self.vapi.assert_negative_api_retval(): self.route_lookup("1.1.1.2/32", True) def test_longest_prefix_match(self): # verify we find lpm lpm_prefix = "1.1.1.0/24" result = self.route_lookup("1.1.1.2/32", False) assert (lpm_prefix == str(result.route.prefix)) # Verify we find the exact when not requested result = self.route_lookup(lpm_prefix, False) assert (lpm_prefix == str(result.route.prefix)) # Can't seem to delete the default route so no negative LPM test. class TestIPv4IfAddrRoute(VppTestCase): """ IPv4 Interface Addr Route Test Case """ @classmethod def setUpClass(cls): super(TestIPv4IfAddrRoute, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPv4IfAddrRoute, cls).tearDownClass() def setUp(self): super(TestIPv4IfAddrRoute, self).setUp() # create 1 pg interface self.create_pg_interfaces(range(1)) for i in self.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() def tearDown(self): super(TestIPv4IfAddrRoute, self).tearDown() for i in self.pg_interfaces: i.unconfig_ip4() i.admin_down() def test_ipv4_ifaddrs_same_prefix(self): """ IPv4 Interface Addresses Same Prefix test Test scenario: - Verify no route in FIB for prefix 10.10.10.0/24 - Configure IPv4 address 10.10.10.10/24 on an interface - Verify route in FIB for prefix 10.10.10.0/24 - Configure IPv4 address 10.10.10.20/24 on an interface - Delete 10.10.10.10/24 from interface - Verify route in FIB for prefix 10.10.10.0/24 - Delete 10.10.10.20/24 from interface - Verify no route in FIB for prefix 10.10.10.0/24 """ # create two addresses, verify route not present if_addr1 = VppIpInterfaceAddress(self, self.pg0, "10.10.10.10", 24) if_addr2 = VppIpInterfaceAddress(self, self.pg0, "10.10.10.20", 24) self.assertFalse(if_addr1.query_vpp_config()) # 10.10.10.10/24 self.assertFalse(find_route(self, "10.10.10.10", 32)) self.assertFalse(find_route(self, "10.10.10.20", 32)) self.assertFalse(find_route(self, "10.10.10.255", 32)) self.assertFalse(find_route(self, "10.10.10.0", 32)) # configure first address, verify route present if_addr1.add_vpp_config() self.assertTrue(if_addr1.query_vpp_config()) # 10.10.10.10/24 self.assertTrue(find_route(self, "10.10.10.10", 32)) self.assertFalse(find_route(self, "10.10.10.20", 32)) self.assertTrue(find_route(self, "10.10.10.255", 32)) self.assertTrue(find_route(self, "10.10.10.0", 32)) # configure second address, delete first, verify route not removed if_addr2.add_vpp_config() if_addr1.remove_vpp_config() self.assertFalse(if_addr1.query_vpp_config()) # 10.10.10.10/24 self.assertTrue(if_addr2.query_vpp_config()) # 10.10.10.20/24 self.assertFalse(find_route(self, "10.10.10.10", 32)) self.assertTrue(find_route(self, "10.10.10.20", 32)) self.assertTrue(find_route(self, "10.10.10.255", 32)) self.assertTrue(find_route(self, "10.10.10.0", 32)) # delete second address, verify route removed if_addr2.remove_vpp_config() self.assertFalse(if_addr2.query_vpp_config()) # 10.10.10.20/24 self.assertFalse(find_route(self, "10.10.10.10", 32)) self.assertFalse(find_route(self, "10.10.10.20", 32)) self.assertFalse(find_route(self, "10.10.10.255", 32)) self.assertFalse(find_route(self, "10.10.10.0", 32)) def test_ipv4_ifaddr_route(self): """ IPv4 Interface Address Route test Test scenario: - Create loopback - Configure IPv4 address on loopback - Verify that address is not in the FIB - Bring loopback up - Verify that address is in the FIB now - Bring loopback down - Verify that address is not in the FIB anymore - Bring loopback up - Configure IPv4 address on loopback - Verify that address is in the FIB now """ # create a loopback and configure IPv4 loopbacks = self.create_loopback_interfaces(1) lo_if = self.lo_interfaces[0] lo_if.local_ip4_prefix_len = 32 lo_if.config_ip4() # The intf was down when addr was added -> entry not in FIB fib4_dump = self.vapi.ip_route_dump(0) self.assertFalse(lo_if.is_ip4_entry_in_fib_dump(fib4_dump)) # When intf is brought up, entry is added lo_if.admin_up() fib4_dump = self.vapi.ip_route_dump(0) self.assertTrue(lo_if.is_ip4_entry_in_fib_dump(fib4_dump)) # When intf is brought down, entry is removed lo_if.admin_down() fib4_dump = self.vapi.ip_route_dump(0) self.assertFalse(lo_if.is_ip4_entry_in_fib_dump(fib4_dump)) # Remove addr, bring up interface, re-add -> entry in FIB lo_if.unconfig_ip4() lo_if.admin_up() lo_if.config_ip4() fib4_dump = self.vapi.ip_route_dump(0) self.assertTrue(lo_if.is_ip4_entry_in_fib_dump(fib4_dump)) def test_ipv4_ifaddr_del(self): """ Delete an interface address that does not exist """ loopbacks = self.create_loopback_interfaces(1) lo = self.lo_interfaces[0] lo.config_ip4() lo.admin_up() # # try and remove pg0's subnet from lo # with self.vapi.assert_negative_api_retval(): self.vapi.sw_interface_add_del_address( sw_if_index=lo.sw_if_index, prefix=self.pg0.local_ip4_prefix, is_add=0) class TestICMPEcho(VppTestCase): """ ICMP Echo Test Case """ @classmethod def setUpClass(cls): super(TestICMPEcho, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestICMPEcho, cls).tearDownClass() def setUp(self): super(TestICMPEcho, self).setUp() # create 1 pg interface self.create_pg_interfaces(range(1)) for i in self.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() def tearDown(self): super(TestICMPEcho, self).tearDown() for i in self.pg_interfaces: i.unconfig_ip4() i.admin_down() def test_icmp_echo(self): """ VPP replies to ICMP Echo Request Test scenario: - Receive ICMP Echo Request message on pg0 interface. - Check outgoing ICMP Echo Reply message on pg0 interface. """ icmp_id = 0xb icmp_seq = 5 icmp_load = b'\x0a' * 18 p_echo_request = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / ICMP(id=icmp_id, seq=icmp_seq) / Raw(load=icmp_load)) self.pg0.add_stream(p_echo_request) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg0.get_capture(1) rx = rx[0] ether = rx[Ether] ipv4 = rx[IP] icmp = rx[ICMP] self.assertEqual(ether.src, self.pg0.local_mac) self.assertEqual(ether.dst, self.pg0.remote_mac) self.assertEqual(ipv4.src, self.pg0.local_ip4) self.assertEqual(ipv4.dst, self.pg0.remote_ip4) self.assertEqual(icmptypes[icmp.type], "echo-reply") self.assertEqual(icmp.id, icmp_id) self.assertEqual(icmp.seq, icmp_seq) self.assertEqual(icmp[Raw].load, icmp_load) class TestIPv4FibCrud(VppTestCase): """ FIB - add/update/delete - ip4 routes Test scenario: - add 1k, - del 100, - add new 1k, - del 1.5k ..note:: Python API is too slow to add many routes, needs replacement. """ def config_fib_many_to_one(self, start_dest_addr, next_hop_addr, count, start=0): """ :param start_dest_addr: :param next_hop_addr: :param count: :return list: added ips with 32 prefix """ routes = [] for i in range(count): r = VppIpRoute(self, start_dest_addr % (i + start), 32, [VppRoutePath(next_hop_addr, 0xffffffff)]) r.add_vpp_config() routes.append(r) return routes def unconfig_fib_many_to_one(self, start_dest_addr, next_hop_addr, count, start=0): routes = [] for i in range(count): r = VppIpR
/*
 * gre.h: types/functions for gre.
 *
 * Copyright (c) 2012 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef included_gre_h
#define included_gre_h

#include <vnet/vnet.h>
#include <vnet/gre/packet.h>
#include <vnet/ip/ip.h>
#include <vnet/pg/pg.h>
#include <vnet/ip/format.h>
#include <vnet/adj/adj_types.h>

extern vnet_hw_interface_class_t gre_hw_interface_class;

typedef enum
{
#define gre_error(n,s) GRE_ERROR_##n,
#include <vnet/gre/error.def>
#undef gre_error
  GRE_N_ERROR,
} gre_error_t;

/**
 * @brief The GRE tunnel type
 */
typedef enum gre_tunnel_type_t_
{
  /**
   * L3 GRE (i.e. this tunnel is in L3 mode)
   */
  GRE_TUNNEL_TYPE_L3 = 0,
  /**
   * Transparent Ethernet Bridging - the tunnel is in L2 mode
   */
  GRE_TUNNEL_TYPE_TEB = 1,
  /**
   * ERSPAN type 2 - the tunnel is for port mirror SPAN output. Each tunnel is
   * associated with a session ID and expected to be used for encap and output
   * of mirrored packet from a L2 network only. There is no support for
   * receiving ERSPAN packets from a GRE ERSPAN tunnel in VPP.
   */
  GRE_TUNNEL_TYPE_ERSPAN = 2,
} gre_tunnel_type_t;

#define GRE_TUNNEL_TYPE_N (GRE_TUNNEL_TYPE_ERSPAN + 1)

#define GRE_TUNNEL_TYPE_NAMES {    \
    [GRE_TUNNEL_TYPE_L3] = "L3",   \
    [GRE_TUNNEL_TYPE_TEB] = "TEB", \
    [GRE_TUNNEL_TYPE_ERSPAN] = "ERSPAN", \
}

/**
 * A GRE payload protocol registration
 */
typedef struct
{
  /** Name (a c string). */
  char *name;

  /** GRE protocol type in host byte order. */
  gre_protocol_t protocol;

  /** GRE tunnel type */
  gre_tunnel_type_t tunnel_type;

  /** Node which handles this type. */
  u32 node_index;

  /** Next index for this type. */
  u32 next_index;
} gre_protocol_info_t;

/**
 * @brief Key for a IPv4 GRE Tunnel
 */
typedef struct gre_tunnel_key4_t_
{
  /**
   * Source and destination IP addresses
   */
  union
  {
    struct
    {
      ip4_address_t gtk_src;
      ip4_address_t gtk_dst;
    };
    u64 gtk_as_u64;
  };

  /**
   * FIB table index, ERSPAN session ID and tunnel type in u32 bit fields:
   * - The FIB table index the src,dst addresses are in, top 20 bits
   * - The Session ID for ERSPAN tunnel type and 0 otherwise, next 10 bits
   * - Tunnel type, bottom 2 bits
   */
  u32 gtk_fidx_ssid_type;
} __attribute__ ((packed)) gre_tunnel_key4_t;

/**
 * @brief Key for a IPv6 GRE Tunnel
 * We use a different type so that the V4 key hash is as small as possible
 */
typedef struct gre_tunnel_key6_t_
{
  /**
   * Source and destination IP addresses
   */
  ip6_address_t gtk_src;
  ip6_address_t gtk_dst;

  /**
   * FIB table index, ERSPAN session ID and tunnel type in u32 bit fields:
   * - The FIB table index the src,dst addresses are in, top 20 bits
   * - The Session ID for ERSPAN tunnel type and 0 otherwise, next 10 bits
   * - Tunnel type, bottom 2 bits
   */
  u32 gtk_fidx_ssid_type;
} __attribute__ ((packed)) gre_tunnel_key6_t;

#define GTK_FIB_INDEX_SHIFT	12
#define GTK_FIB_INDEX_MASK	0xfffff000
#define GTK_TYPE_SHIFT		0
#define GTK_TYPE_MASK		0x3
#define GTK_SESSION_ID_SHIFT	2
#define GTK_SESSION_ID_MASK	0xffc
#define GTK_SESSION_ID_MAX	(GTK_SESSION_ID_MASK >> GTK_SESSION_ID_SHIFT)

/**
 * Union of the two possible key types
 */
typedef union gre_tunnel_key_t_
{
  gre_tunnel_key4_t gtk_v4;
  gre_tunnel_key6_t gtk_v6;
} gre_tunnel_key_t;

/**
 * Used for GRE header seq number generation for ERSPAN encap
 */
typedef struct
{
  u32 seq_num;
  u32 ref_count;
} gre_sn_t;

/**
 * Hash key for GRE header seq number generation for ERSPAN encap
 */
typedef struct
{
  ip46_address_t src;
  ip46_address_t dst;
  u32 fib_index;
} gre_sn_key_t;

/**
 * @brief A representation of a GRE tunnel
 */
typedef struct
{
  /**
   * Required for pool_get_aligned
   */
  CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);

  /**
   * The hash table's key stored in separate memory since the tunnel_t
   * memory can realloc.
   */
  gre_tunnel_key_t *key;

  /**
   * The tunnel's source/local address
   */
  ip46_address_t tunnel_src;
  /**
   * The tunnel's destination/remote address
   */
  fib_prefix_t tunnel_dst;
  /**
   * The FIB in which the src.dst address are present
   */
  u32 outer_fib_index;
  u32 hw_if_index;
  u32 sw_if_index;
  gre_tunnel_type_t type;

  /**
   * an L2 tunnel always rquires an L2 midchain. cache here for DP.
   */
  adj_index_t l2_adj_index;

  /**
   * ERSPAN type 2 session ID, least significant 10 bits of u16
   */
  u16 session_id;

  /**
   * GRE header sequence number (SN) used for ERSPAN type 2 header, must be
   * bumped automically to be thread safe. As multiple GRE tunnels are created
   * for the same fib-idx/DIP/SIP with different ERSPAN session number, they all
   * share the same SN which is kept per FIB/DIP/SIP, as specified by RFC2890.
   */
  gre_sn_t *gre_sn;


  u32 dev_instance;		/* Real device instance in tunnel vector */
  u32 user_instance;		/* Instance name being shown to user */
} gre_tunnel_t;

typedef struct
{
  u8 next_index;
  u8 tunnel_type;
} next_info_t;

/**
 * @brief GRE related global data
 */
typedef struct
{
  /**
   * pool of tunnel instances
   */
  gre_tunnel_t *tunnels;

  /**
   * GRE payload protocol registrations
   */
  gre_protocol_info_t *protocol_infos;

  /**
   *  Hash tables mapping name/protocol to protocol info index.
   */
  uword *protocol_info_by_name, *protocol_info_by_protocol;

  /**
   * Hash mapping to tunnels with ipv4 src/dst addr
   */
  uword *tunnel_by_key4;

  /**
   * Hash mapping to tunnels with ipv6 src/dst addr
   */
  uword *tunnel_by_key6;

  /**
   * Hash mapping tunnel src/dst addr and fib-idx to sequence number
   */
  uword *seq_num_by_key;

  /**
   * Mapping from sw_if_index to tunnel index
   */
  u32 *tunnel_index_by_sw_if_index;

  /* Sparse vector mapping gre protocol in network byte order
     to next index. */
  next_info_t *next_by_protocol;

  /* convenience */
  vlib_main_t *vlib_main;
  vnet_main_t *vnet_main;

  /* Record used instances */
  uword *instance_used;
} gre_main_t;

/**
 * @brief IPv4 and GRE header.
 */
/* *INDENT-OFF* */
typedef CLIB_PACKED (struct {
  ip4_header_t ip4;
  gre_header_t gre;
}) ip4_and_gre_header_t;
/* *INDENT-ON* */

/**
 * @brief IPv6 and GRE header.
 */
/* *INDENT-OFF* */
typedef CLIB_PACKED (struct {
  ip6_header_t ip6;
  gre_header_t gre;
}) ip6_and_gre_header_t;
/* *INDENT-ON* */

always_inline gre_protocol_info_t *
gre_get_protocol_info (gre_main_t * em, gre_protocol_t protocol)
{
  uword *p = hash_get (em->protocol_info_by_protocol, protocol);
  return p ? vec_elt_at_index (em->protocol_infos, p[0]) : 0;
}

extern gre_main_t gre_main;

extern clib_error_t *gre_interface_admin_up_down (vnet_main_t * vnm,
						  u32 hw_if_index, u32 flags);

extern void gre_tunnel_stack (adj_index_t ai);
extern void gre_update_adj (vnet_main_t * vnm,
			    u32 sw_if_index, adj_index_t ai);

format_function_t format_gre_protocol;
format_function_t format_gre_header;
format_function_t format_gre_header_with_length;

extern vlib_node_registration_t gre4_input_node;
extern vlib_node_registration_t gre6_input_node;
extern vlib_node_registration_t gre_encap_node;
extern vnet_device_class_t gre_device_class;

/* Parse gre protocol as 0xXXXX or protocol name.
   In either host or network byte order. */
unformat_function_t unformat_gre_protocol_host_byte_order;
unformat_function_t unformat_gre_protocol_net_byte_order;

/* Parse gre header. */
unformat_function_t unformat_gre_header;
unformat_function_t unformat_pg_gre_header;

void
gre_register_input_protocol (vlib_main_t * vm, gre_protocol_t protocol,
			     u32 node_index, gre_tunnel_type_t tunnel_type);

/* manually added to the interface output node in gre.c */
#define GRE_OUTPUT_NEXT_LOOKUP	1

typedef struct
{
  u8 is_add;
  gre_tunnel_type_t type;
  u8 is_ipv6;
  u32 instance;
  ip46_address_t src, dst;
  u32 outer_fib_id;
  u16 session_id;
} vnet_gre_tunnel_add_del_args_t;

extern int vnet_gre_tunnel_add_del (vnet_gre_tunnel_add_del_args_t * a,
				    u32 * sw_if_indexp);

static inline void
gre_mk_key4 (ip4_address_t src,
	     ip4_address_t dst,
	     u32 fib_index, u8 ttype, u16 session_id, gre_tunnel_key4_t * key)
{
  key->gtk_src = src;
  key->gtk_dst = dst;
  key->gtk_fidx_ssid_type = ttype |
    (fib_index << GTK_FIB_INDEX_SHIFT) | (session_id << GTK_SESSION_ID_SHIFT);
}

static inline int
gre_match_key4 (const gre_tunnel_key4_t * key1,
		const gre_tunnel_key4_t * key2)
{
  return ((key1->gtk_as_u64 == key2->gtk_as_u64) &&
	  (key1->gtk_fidx_ssid_type == key2->gtk_fidx_ssid_type));
}

static inline void
gre_mk_key6 (const ip6_address_t * src,
	     const ip6_address_t * dst,
	     u32 fib_index, u8 ttype, u16 session_id, gre_tunnel_key6_t * key)
{
  key->gtk_src = *src;
  key->gtk_dst = *dst;
  key->gtk_fidx_ssid_type = ttype |
    (fib_index << GTK_FIB_INDEX_SHIFT) | (session_id << GTK_SESSION_ID_SHIFT);
}

static inline int
gre_match_key6 (const gre_tunnel_key6_t * key1,
		const gre_tunnel_key6_t * key2)
{
  return ((key1->gtk_src.as_u64[0] == key2->gtk_src.as_u64[0]) &&
	  (key1->gtk_src.as_u64[1] == key2->gtk_src.as_u64[1]) &&
	  (key1->gtk_dst.as_u64[0] == key2->gtk_dst.as_u64[0]) &&
	  (key1->gtk_dst.as_u64[1] == key2->gtk_dst.as_u64[1]) &&
	  (key1->gtk_fidx_ssid_type == key2->gtk_fidx_ssid_type));
}

static inline void
gre_mk_sn_key (const gre_tunnel_t * gt, gre_sn_key_t * key)
{
  key->src = gt->tunnel_src;
  key->dst = gt->tunnel_dst.fp_addr;
  key->fib_index = gt->outer_fib_index;
}

#endif /* included_gre_h */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
ed for: # 1 - another destination address lookup # 2 - a source address lookup # table_dst = VppIpTable(self, 1) table_src = VppIpTable(self, 2) table_dst.add_vpp_config() table_src.add_vpp_config() # # Add a route in the default table to point to a deag/ # second lookup in each of these tables # route_to_dst = VppIpRoute(self, "1.1.1.1", 32, [VppRoutePath("0.0.0.0", 0xffffffff, nh_table_id=1)]) route_to_src = VppIpRoute( self, "1.1.1.2", 32, [VppRoutePath("0.0.0.0", 0xffffffff, nh_table_id=2, type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP)]) route_to_dst.add_vpp_config() route_to_src.add_vpp_config() # # packets to these destination are dropped, since they'll # hit the respective default routes in the second table # p_dst = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="5.5.5.5", dst="1.1.1.1") / TCP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) p_src = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="2.2.2.2", dst="1.1.1.2") / TCP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) pkts_dst = p_dst * 257 pkts_src = p_src * 257 self.send_and_assert_no_replies(self.pg0, pkts_dst, "IP in dst table") self.send_and_assert_no_replies(self.pg0, pkts_src, "IP in src table") # # add a route in the dst table to forward via pg1 # route_in_dst = VppIpRoute(self, "1.1.1.1", 32, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], table_id=1) route_in_dst.add_vpp_config() self.send_and_expect(self.pg0, pkts_dst, self.pg1) # # add a route in the src table to forward via pg2 # route_in_src = VppIpRoute(self, "2.2.2.2", 32, [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)], table_id=2) route_in_src.add_vpp_config() self.send_and_expect(self.pg0, pkts_src, self.pg2) # # loop in the lookup DP # route_loop = VppIpRoute(self, "2.2.2.3", 32, [VppRoutePath("0.0.0.0", 0xffffffff, nh_table_id=0)]) route_loop.add_vpp_config() p_l = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="2.2.2.4", dst="2.2.2.3") / TCP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) self.send_and_assert_no_replies(self.pg0, p_l * 257, "IP lookup loop") class TestIPInput(VppTestCase): """ IPv4 Input Exceptions """ @classmethod def setUpClass(cls): super(TestIPInput, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPInput, cls).tearDownClass() def setUp(self): super(TestIPInput, self).setUp() self.create_pg_interfaces(range(2)) for i in self.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() def tearDown(self): super(TestIPInput, self).tearDown() for i in self.pg_interfaces: i.unconfig_ip4() i.admin_down() def test_ip_input(self): """ IP Input Exceptions """ # i can't find a way in scapy to construct an IP packet # with a length less than the IP header length # # Packet too short - this is forwarded # p_short = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, len=40) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) rx = self.send_and_expect(self.pg0, p_short * NUM_PKTS, self.pg1) # # Packet too long - this is dropped # p_long = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, len=400) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) rx = self.send_and_assert_no_replies(self.pg0, p_long * NUM_PKTS, "too long") # # bad chksum - this is dropped # p_chksum = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, chksum=400) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) rx = self.send_and_assert_no_replies(self.pg0, p_chksum * NUM_PKTS, "bad checksum") # # bad version - this is dropped # p_ver = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, version=3) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) rx = self.send_and_assert_no_replies(self.pg0, p_ver * NUM_PKTS, "funky version") # # fragment offset 1 - this is dropped # p_frag = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, frag=1) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) rx = self.send_and_assert_no_replies(self.pg0, p_frag * NUM_PKTS, "frag offset") # # TTL expired packet # p_ttl = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=1) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 100)) rx = self.send_and_expect(self.pg0, p_ttl * NUM_PKTS, self.pg0) rx = rx[0] icmp = rx[ICMP] self.assertEqual(icmptypes[icmp.type], "time-exceeded") self.assertEqual(icmpcodes[icmp.type][icmp.code], "ttl-zero-during-transit") self.assertEqual(icmp.src, self.pg0.remote_ip4) self.assertEqual(icmp.dst, self.pg1.remote_ip4) # # MTU exceeded # p_mtu = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=10, flags='DF') / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 2000)) self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1500, 0, 0, 0]) rx = self.send_and_expect(self.pg0, p_mtu * NUM_PKTS, self.pg0) rx = rx[0] icmp = rx[ICMP] self.assertEqual(icmptypes[icmp.type], "dest-unreach") self.assertEqual(icmpcodes[icmp.type][icmp.code], "fragmentation-needed") self.assertEqual(icmp.src, self.pg0.remote_ip4) self.assertEqual(icmp.dst, self.pg1.remote_ip4) self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2500, 0, 0, 0]) rx = self.send_and_expect(self.pg0, p_mtu * NUM_PKTS, self.pg1) # Reset MTU for subsequent tests self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [9000, 0, 0, 0]) # # source address 0.0.0.0 and 25.255.255.255 and for-us # p_s0 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="0.0.0.0", dst=self.pg0.local_ip4) / ICMP(id=4, seq=4) / Raw(load=b'\x0a' * 18)) rx = self.send_and_assert_no_replies(self.pg0, p_s0 * 17) p_s0 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="255.255.255.255", dst=self.pg0.local_ip4) / ICMP(id=4, seq=4) / Raw(load=b'\x0a' * 18)) rx = self.send_and_assert_no_replies(self.pg0, p_s0 * 17) class TestIPDirectedBroadcast(VppTestCase): """ IPv4 Directed Broadcast """ @classmethod def setUpClass(cls): super(TestIPDirectedBroadcast, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPDirectedBroadcast, cls).tearDownClass() def setUp(self): super(TestIPDirectedBroadcast, self).setUp() self.create_pg_interfaces(range(2)) for i in self.pg_interfaces: i.admin_up() def tearDown(self): super(TestIPDirectedBroadcast, self).tearDown() for i in self.pg_interfaces: i.admin_down() def test_ip_input(self): """ IP Directed Broadcast """ # # set the directed broadcast on pg0 first, then config IP4 addresses # for pg1 directed broadcast is always disabled self.vapi.sw_interface_set_ip_directed_broadcast( self.pg0.sw_if_index, 1) p0 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / IP(src="1.1.1.1", dst=self.pg0._local_ip4_bcast) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 2000)) p1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="1.1.1.1", dst=self.pg1._local_ip4_bcast) / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 2000)) self.pg0.config_ip4() self.pg0.resolve_arp() self.pg1.config_ip4() self.pg1.resolve_arp() # # test packet is L2 broadcast # rx = self.send_and_expect(self.pg1, p0 * NUM_PKTS, self.pg0) self.assertTrue(rx[0][Ether].dst, "ff:ff:ff:ff:ff:ff") self.send_and_assert_no_replies(self.pg0, p1 * NUM_PKTS, "directed broadcast disabled") # # toggle directed broadcast on pg0 # self.vapi.sw_interface_set_ip_directed_broadcast( self.pg0.sw_if_index, 0) self.send_and_assert_no_replies(self.pg1, p0 * NUM_PKTS, "directed broadcast disabled") self.vapi.sw_interface_set_ip_directed_broadcast( self.pg0.sw_if_index, 1) rx = self.send_and_expect(self.pg1, p0 * NUM_PKTS, self.pg0) self.pg0.unconfig_ip4() self.pg1.unconfig_ip4() class TestIPLPM(VppTestCase): """ IPv4 longest Prefix Match """ @classmethod def setUpClass(cls): super(TestIPLPM, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPLPM, cls).tearDownClass() def setUp(self): super(TestIPLPM, self).setUp() self.create_pg_interfaces(range(4)) for i in self.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() def tearDown(self): super(TestIPLPM, self).tearDown() for i in self.pg_interfaces: i.admin_down() i.unconfig_ip4() def test_ip_lpm(self): """ IP longest Prefix Match """ s_24 = VppIpRoute(self, "10.1.2.0", 24, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)]) s_24.add_vpp_config() s_8 = VppIpRoute(self, "10.0.0.0", 8, [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)]) s_8.add_vpp_config() p_8 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="1.1.1.1", dst="10.1.1.1") / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 2000)) p_24 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(src="1.1.1.1", dst="10.1.2.1") / UDP(sport=1234, dport=1234) / Raw(b'\xa5' * 2000)) self.logger.info(self.vapi.cli("sh ip fib mtrie")) rx = self.send_and_expect(self.pg0, p_8 * NUM_PKTS, self.pg2) rx = self.send_and_expect(self.pg0, p_24 * NUM_PKTS, self.pg1) @tag_fixme_vpp_workers class TestIPv4Frag(VppTestCase): """ IPv4 fragmentation """ @classmethod def setUpClass(cls): super(TestIPv4Frag, cls).setUpClass() cls.create_pg_interfaces([0, 1]) cls.src_if = cls.pg0 cls.dst_if = cls.pg1 # setup all interfaces for i in cls.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() @classmethod def tearDownClass(cls): super(TestIPv4Frag, cls).tearDownClass() def test_frag_large_packets(self): """ Fragmentation of large packets """ self.vapi.cli("adjacency counters enable") p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw()) self.extend_packet(p, 6000, "abcde") saved_payload = p[Raw].load nbr = VppNeighbor(self, self.dst_if.sw_if_index, self.dst_if.remote_mac, self.dst_if.remote_ip4).add_vpp_config() # Force fragmentation by setting MTU of output interface # lower than packet size self.vapi.sw_interface_set_mtu(self.dst_if.sw_if_index, [5000, 0, 0, 0]) self.pg_enable_capture() self.src_if.add_stream(p) self.pg_start() # Expecting 3 fragments because size of created fragments currently # cannot be larger then VPP buffer size (which is 2048) packets = self.dst_if.get_capture(3) # we should show 3 packets thru the neighbor self.assertEqual(3, nbr.get_stats()['packets']) # Assume VPP sends the fragments in order payload = b'' for p in packets: payload_offset = p.frag * 8 if payload_offset > 0: payload_offset -= 8 # UDP header is not in payload self.assert_equal(payload_offset, len(payload)) payload += p[Raw].load self.assert_equal(payload, saved_payload, "payload") class TestIPReplace(VppTestCase): """ IPv4 Table Replace """ @classmethod def setUpClass(cls): super(TestIPReplace, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPReplace, cls).tearDownClass() def setUp(self): super(TestIPReplace, self).setUp() self.create_pg_interfaces(range(4)) table_id = 1 self.tables = [] for i in self.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() i.generate_remote_hosts(2) self.tables.append(VppIpTable(self, table_id).add_vpp_config()) table_id += 1 def tearDown(self): super(TestIPReplace, self).tearDown() for i in self.pg_interfaces: i.admin_down() i.unconfig_ip4() def test_replace(self): """ IP Table Replace """ MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t N_ROUTES = 20 links = [self.pg0, self.pg1, self.pg2, self.pg3] routes = [[], [], [], []] # load up the tables with some routes for ii, t in enumerate(self.tables): for jj in range(N_ROUTES): uni = VppIpRoute( self, "10.0.0.%d" % jj, 32, [VppRoutePath(links[ii].remote_hosts[0].ip4, links[ii].sw_if_index), VppRoutePath(links[ii].remote_hosts[1].ip4, links[ii].sw_if_index)], table_id=t.table_id).add_vpp_config() multi = VppIpMRoute( self, "0.0.0.0", "239.0.0.%d" % jj, 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, [VppMRoutePath(self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), VppMRoutePath(self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), VppMRoutePath(self.pg2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), VppMRoutePath(self.pg3.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)], table_id=t.table_id).add_vpp_config() routes[ii].append({'uni': uni, 'multi': multi}) # # replace the tables a few times # for kk in range(3): # replace_begin each table for t in self.tables: t.replace_begin() # all the routes are still there for ii, t in enumerate(self.tables): dump = t.dump() mdump = t.mdump() for r in routes[ii]: self.assertTrue(find_route_in_dump(dump, r['uni'], t)) self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t)) # redownload the even numbered routes for ii, t in enumerate(self.tables): for jj in range(0, N_ROUTES, 2): routes[ii][jj]['uni'].add_vpp_config() routes[ii][jj]['multi'].add_vpp_config() # signal each table replace_end for t in self.tables: t.replace_end() # we should find the even routes, but not the odd for ii, t in enumerate(self.tables): dump = t.dump() mdump = t.mdump() for jj in range(0, N_ROUTES, 2): self.assertTrue(find_route_in_dump( dump, routes[ii][jj]['uni'], t)) self.assertTrue(find_mroute_in_dump( mdump, routes[ii][jj]['multi'], t)) for jj in range(1, N_ROUTES - 1, 2): self.assertFalse(find_route_in_dump( dump, routes[ii][jj]['uni'], t)) self.assertFalse(find_mroute_in_dump( mdump, routes[ii][jj]['multi'], t)) # reload all the routes for ii, t in enumerate(self.tables): for r in routes[ii]: r['uni'].add_vpp_config() r['multi'].add_vpp_config() # all the routes are still there for ii, t in enumerate(self.tables): dump = t.dump() mdump = t.mdump() for r in routes[ii]: self.assertTrue(find_route_in_dump(dump, r['uni'], t)) self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t)) # # finally flush the tables for good measure # for t in self.tables: t.flush() self.assertEqual(len(t.dump()), 5) self.assertEqual(len(t.mdump()), 3) class TestIPCover(VppTestCase): """ IPv4 Table Cover """ @classmethod def setUpClass(cls): super(TestIPCover, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIPCover, cls).tearDownClass() def setUp(self): super(TestIPCover, self).setUp() self.create_pg_interfaces(range(4)) table_id = 1 self.tables = [] for i in self.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() i.generate_remote_hosts(2) self.tables.append(VppIpTable(self, table_id).add_vpp_config()) table_id += 1 def tearDown(self): super(TestIPCover, self).tearDown() for i in self.pg_interfaces: i.admin_down() i.unconfig_ip4() def test_cover(self): """ IP Table Cover """ # add a loop back with a /32 prefix lo = VppLoInterface(self) lo.admin_up() a = VppIpInterfaceAddress(self, lo, "127.0.0.1", 32).add_vpp_config() # add a neighbour that matches the loopback's /32 nbr = VppNeighbor(self, lo.sw_if_index, lo.remote_mac, "127.0.0.1").add_vpp_config() # add the default route which will be the cover for /32 r = VppIpRoute(self, "0.0.0.0", 0, [VppRoutePath("127.0.0.1", lo.sw_if_index)], register=False).add_vpp_config() # add/remove/add a longer mask cover r8 = VppIpRoute(self, "127.0.0.0", 8, [VppRoutePath("127.0.0.1", lo.sw_if_index)]).add_vpp_config() r8.remove_vpp_config() r8.add_vpp_config() r8.remove_vpp_config() # remove the default route r.remove_vpp_config() # remove the interface prefix a.remove_vpp_config() class TestIP4Replace(VppTestCase): """ IPv4 Interface Address Replace """ @classmethod def setUpClass(cls): super(TestIP4Replace, cls).setUpClass() @classmethod def tearDownClass(cls): super(TestIP4Replace, cls).tearDownClass() def setUp(self): super(TestIP4Replace, self).setUp() self.create_pg_interfaces(range(4)) for i in self.pg_interfaces: i.admin_up() def tearDown(self): super(TestIP4Replace, self).tearDown() for i in self.pg_interfaces: i.admin_down() def get_n_pfxs(self, intf): return len(self.vapi.ip_address_dump(intf.sw_if_index)) def test_replace(self): """ IP interface address replace """ intf_pfxs = [[], [], [], []] # add prefixes to each of the interfaces for i in range(len(self.pg_interfaces)): intf = self.pg_interfaces[i] # 172.16.x.1/24 addr = "172.16.%d.1" % intf.sw_if_index a = VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config() intf_pfxs[i].append(a) # 172.16.x.2/24 - a different address in the same subnet as above addr = "172.16.%d.2" % intf.sw_if_index a = VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config() intf_pfxs[i].append(a) # 172.15.x.2/24 - a different address and subnet addr = "172.15.%d.2" % intf.sw_if_index a = VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config() intf_pfxs[i].append(a) # a dump should n_address in it for intf in self.pg_interfaces: self.assertEqual(self.get_n_pfxs(intf), 3) # # remove all the address thru a replace # self.vapi.sw_interface_address_replace_begin() self.vapi.sw_interface_address_replace_end() for intf in self.pg_interfaces: self.assertEqual(self.get_n_pfxs(intf), 0) # # add all the interface addresses back # for p in intf_pfxs: for v in p: v.add_vpp_config() for intf in self.pg_interfaces: self.assertEqual(self.get_n_pfxs(intf), 3) # # replace again, but this time update/re-add the address on the first # two interfaces # self.vapi.sw_interface_address_replace_begin() for p in intf_pfxs[:2]: for v in p: v.add_vpp_config() self.vapi.sw_interface_address_replace_end() # on the first two the address still exist, # on the other two they do not for intf in self.pg_interfaces[:2]: self.assertEqual(self.get_n_pfxs(intf), 3) for p in intf_pfxs[:2]: for v in p: self.assertTrue(v.query_vpp_config()) for intf in self.pg_interfaces[2:]: self.assertEqual(self.get_n_pfxs(intf), 0) # # add all the interface addresses back on the last two # for p in intf_pfxs[2:]: for v in p: v.add_vpp_config() for intf in self.pg_interfaces: self.assertEqual(self.get_n_pfxs(intf), 3) # # replace again, this time add different prefixes on all the interfaces # self.vapi.sw_interface_address_replace_begin() pfxs = [] for intf in self.pg_interfaces: # 172.18.x.1/24 addr = "172.18.%d.1" % intf.sw_if_index pfxs.append(VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config()) self.vapi.sw_interface_address_replace_end() # only .18 should exist on each interface for intf in self.pg_interfaces: self.assertEqual(self.get_n_pfxs(intf), 1) for pfx in pfxs: self.assertTrue(pfx.query_vpp_config()) # # remove everything # self.vapi.sw_interface_address_replace_begin() self.vapi.sw_interface_address_replace_end() for intf in self.pg_interfaces: self.assertEqual(self.get_n_pfxs(intf), 0) # # add prefixes to each interface. post-begin add the prefix from # interface X onto interface Y. this would normally be an error # since it would generate a 'duplicate address' warning. but in # this case, since what is newly downloaded is sane, it's ok # for intf in self.pg_interfaces: # 172.18.x.1/24 addr = "172.18.%d.1" % intf.sw_if_index VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config() self.vapi.sw_interface_address_replace_begin() pfxs = [] for intf in self.pg_interfaces: # 172.18.x.1/24 addr = "172.18.%d.1" % (intf.sw_if_index + 1) pfxs.append(VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config()) self.vapi.sw_interface_address_replace_end() self.logger.info(self.vapi.cli("sh int addr")) for intf in self.pg_interfaces: self.assertEqual(self.get_n_pfxs(intf), 1) for pfx in pfxs: self.assertTrue(pfx.query_vpp_config()) class TestIPv4PathMTU(VppTestCase): """ IPv4 Path MTU """ @classmethod def setUpClass(cls): super(TestIPv4PathMTU, cls).setUpClass() cls.create_pg_interfaces(range(2)) # setup all interfaces for i in cls.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() @classmethod def tearDownClass(cls): super(TestIPv4PathMTU, cls).tearDownClass() def test_path_mtu(self): """ Path MTU """ # # The goal here is not to test that fragmentation works correctly, # that's done elsewhere, the intent is to ensure that the Path MTU # settings are honoured. # self.vapi.cli("adjacency counters enable") # set the interface MTU to a reasonable value self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1800, 0, 0, 0]) self.pg1.generate_remote_hosts(4) p_2k = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(b'0xa' * 640)) p_1k = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(b'0xa' * 320)) nbr = VppNeighbor(self, self.pg1.sw_if_index, self.pg1.remote_mac, self.pg1.remote_ip4).add_vpp_config() # this is now the interface MTU frags self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2) self.send_and_expect(self.pg0, [p_1k], self.pg1) # drop the path MTU for this neighbour to below the interface MTU # expect more frags pmtu = VppIpPathMtu(self, self.pg1.remote_ip4, 900).add_vpp_config() self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # print/format the adj delegate self.logger.info(self.vapi.cli("sh adj 5")) # increase the path MTU to more than the interface # expect to use the interface MTU pmtu.modify(8192) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2) self.send_and_expect(self.pg0, [p_1k], self.pg1) # go back to an MTU from the path # wrap the call around mark-n-sweep to enusre updates clear stale self.vapi.ip_path_mtu_replace_begin() pmtu.modify(900) self.vapi.ip_path_mtu_replace_end() self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # raise the interface's MTU # should still use that of the path self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # set path high and interface low pmtu.modify(2000) self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [900, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # remove the path MTU using the mark-n-sweep semantics self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1800, 0, 0, 0]) self.vapi.ip_path_mtu_replace_begin() self.vapi.ip_path_mtu_replace_end() self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2) self.send_and_expect(self.pg0, [p_1k], self.pg1) # # set path MTU for a neighbour that doesn't exist, yet # pmtu2 = VppIpPathMtu(self, self.pg1.remote_hosts[2].ip4, 900).add_vpp_config() p_2k = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4) / UDP(sport=1234, dport=5678) / Raw(b'0xa' * 640)) p_1k = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4) / UDP(sport=1234, dport=5678) / Raw(b'0xa' * 320)) nbr2 = VppNeighbor(self, self.pg1.sw_if_index, self.pg1.remote_hosts[2].mac, self.pg1.remote_hosts[2].ip4).add_vpp_config() # should frag to the path MTU self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # remove and re-add the neighbour nbr2.remove_vpp_config() nbr2.add_vpp_config() # should frag to the path MTU self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # # set PMTUs for many peers # N_HOSTS = 16 self.pg1.generate_remote_hosts(16) self.pg1.configure_ipv4_neighbors() for h in range(N_HOSTS): pmtu = VppIpPathMtu(self, self.pg1.remote_hosts[h].ip4, 900) pmtu.add_vpp_config() self.assertTrue(pmtu.query_vpp_config()) self.logger.info(self.vapi.cli("sh ip pmtu")) dump = list(self.vapi.vpp.details_iter(self.vapi.ip_path_mtu_get)) self.assertEqual(N_HOSTS, len(dump)) for h in range(N_HOSTS): p_2k[IP].dst = self.pg1.remote_hosts[h].ip4 p_1k[IP].dst = self.pg1.remote_hosts[h].ip4 # should frag to the path MTU self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) if __name__ == '__main__': unittest.main(testRunner=VppTestRunner)