#!/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 VppTestCase, VppTestRunner from util import ppp from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpMRoute, \ VppMRoutePath, MRouteItfFlags, MRouteEntryFlags, VppMplsIpBind, \ VppMplsTable, VppIpTable, FibPathType, find_route, \ VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump 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 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)) 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 = VppIpRoute(self, start_dest_addr % (i + start), 32, [VppRoutePath(next_hop_addr, 0xffffffff)]) r.remove_vpp_config() routes.append(r) return routes def create_stream(self, src_if, dst_if, routes, count): pkts = [] for _ in range(count): dst_addr = random.choice(routes).prefix.network_address info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(info) p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / IP(src=src_if.remote_ip4, dst=str(dst_addr)) / UDP(sport=1234, dport=1234) / Raw(payload)) info.data = p.copy() self.extend_packet(p, random.choice(self.pg_if_packet_sizes)) pkts.append(p) return pkts def _find_ip_match(self, find_in, pkt): for p in find_in: if self.payload_to_info(p[Raw]) == \ self.payload_to_info(pkt[Raw]): if p[IP].src != pkt[IP].src: break if p[IP].dst != pkt[IP].dst: break if p[UDP].sport != pkt[UDP].sport: break if p[UDP].dport != pkt[UDP].dport: break return p return None def verify_capture(self, dst_interface, received_pkts, expec
/*
 *------------------------------------------------------------------
 * bfd_api.c - bfd api
 *
 * Copyright (c) 2016 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.
 *------------------------------------------------------------------
 */
/**
 * @file
 * @brief BFD binary API implementation
 */

#include <vnet/vnet.h>
#include <vlibmemory/api.h>

#include <vnet/interface.h>
#include <vnet/api_errno.h>
#include <vnet/bfd/bfd_main.h>
#include <vnet/bfd/bfd_api.h>
#include <vnet/ip/ip_types_api.h>

#include <vnet/vnet_msg_enum.h>

#define vl_typedefs		/* define message structures */
#include <vnet/vnet_all_api_h.h>
#undef vl_typedefs

#define vl_endianfun		/* define message structures */
#include <vnet/vnet_all_api_h.h>
#undef vl_endianfun

/* instantiate all the print functions we know about */
#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
#define vl_printfun
#include <vnet/vnet_all_api_h.h>
#undef vl_printfun

#include <vlibapi/api_helper_macros.h>

#define foreach_vpe_api_msg                                \
  _ (BFD_UDP_ADD, bfd_udp_add)                             \
  _ (BFD_UDP_MOD, bfd_udp_mod)                             \
  _ (BFD_UDP_DEL, bfd_udp_del)                             \
  _ (BFD_UDP_SESSION_DUMP, bfd_udp_session_dump)           \
  _ (BFD_UDP_SESSION_SET_FLAGS, bfd_udp_session_set_flags) \
  _ (WANT_BFD_EVENTS, want_bfd_events)                     \
  _ (BFD_AUTH_SET_KEY, bfd_auth_set_key)                   \
  _ (BFD_AUTH_DEL_KEY, bfd_auth_del_key)                   \
  _ (BFD_AUTH_KEYS_DUMP, bfd_auth_keys_dump)               \
  _ (BFD_UDP_AUTH_ACTIVATE, bfd_udp_auth_activate)         \
  _ (BFD_UDP_AUTH_DEACTIVATE, bfd_udp_auth_deactivate)     \
  _ (BFD_UDP_SET_ECHO_SOURCE, bfd_udp_set_echo_source)     \
  _ (BFD_UDP_DEL_ECHO_SOURCE, bfd_udp_del_echo_source)     \
  _ (BFD_UDP_GET_ECHO_SOURCE, bfd_udp_get_echo_source)

pub_sub_handler (bfd_events, BFD_EVENTS);

#define BFD_UDP_API_PARAM_COMMON_CODE                                         \
  ip46_address_t local_addr;                                                  \
  ip46_address_t peer_addr;                                                   \
  ip_address_decode(&mp->local_addr, &local_addr);                             \
  ip_address_decode(&mp->peer_addr, &peer_addr);

#define BFD_UDP_API_PARAM_FROM_MP(mp) \
  clib_net_to_host_u32 (mp->sw_if_index), &local_addr, &peer_addr

static void
vl_api_bfd_udp_add_t_handler (vl_api_bfd_udp_add_t * mp)
{
  vl_api_bfd_udp_add_reply_t *rmp;
  int rv;

  VALIDATE_SW_IF_INDEX (mp);

  BFD_UDP_API_PARAM_COMMON_CODE;

  rv = bfd_udp_add_session (BFD_UDP_API_PARAM_FROM_MP (mp),
			    clib_net_to_host_u32 (mp->desired_min_tx),
			    clib_net_to_host_u32 (mp->required_min_rx),
			    mp->detect_mult, mp->is_authenticated,
			    clib_net_to_host_u32 (mp->conf_key_id),
			    mp->bfd_key_id);

  BAD_SW_IF_INDEX_LABEL;
  REPLY_MACRO (VL_API_BFD_UDP_ADD_REPLY);
}

static void
vl_api_bfd_udp_mod_t_handler (vl_api_bfd_udp_mod_t * mp)
{
  vl_api_bfd_udp_mod_reply_t *rmp;
  int rv;

  VALIDATE_SW_IF_INDEX (mp);

  BFD_UDP_API_PARAM_COMMON_CODE;

  rv = bfd_udp_mod_session (BFD_UDP_API_PARAM_FROM_MP (mp),
			    clib_net_to_host_u32 (mp->desired_min_tx),
			    clib_net_to_host_u32 (mp->required_min_rx),
			    mp->detect_mult);

  BAD_SW_IF_INDEX_LABEL;
  REPLY_MACRO (VL_API_BFD_UDP_MOD_REPLY);
}

static void
vl_api_bfd_udp_del_t_handler (vl_api_bfd_udp_del_t * mp)
{
  vl_api_bfd_udp_del_reply_t *rmp;
  int rv;

  VALIDATE_SW_IF_INDEX (mp);

  BFD_UDP_API_PARAM_COMMON_CODE;

  rv = bfd_udp_del_session (BFD_UDP_API_PARAM_FROM_MP (mp));

  BAD_SW_IF_INDEX_LABEL;
  REPLY_MACRO (VL_API_BFD_UDP_DEL_REPLY);
}

void
send_bfd_udp_session_details (vl_api_registration_t * reg, u32 context,
			      bfd_session_t * bs)
{
  if (bs->transport != BFD_TRANSPORT_UDP4 &&
      bs->transport != BFD_TRANSPORT_UDP6)
    {
      return;
    }

  vl_api_bfd_udp_session_details_t *mp = vl_msg_api_alloc (sizeof (*mp));
  clib_memset (mp, 0, sizeof (*mp));
  mp->_vl_msg_id = ntohs (VL_API_BFD_UDP_SESSION_DETAILS);
  mp->context = context;
  mp->state = clib_host_to_net_u32 (bs->local_state);
  bfd_udp_session_t *bus = &bs->udp;
  bfd_udp_key_t *key = &bus->key;
  mp->sw_if_index = clib_host_to_net_u32 (key->sw_if_index);
  if ((!bs->auth.is_delayed && bs->auth.curr_key) ||
      (bs->auth.is_delayed && bs->auth.next_key))
    {
      mp->is_authenticated = true;
    }
  if (bs->auth.is_delayed && bs->auth.next_key)
    {
      mp->bfd_key_id = bs->auth.next_bfd_key_id;
      mp->conf_key_id = clib_host_to_net_u32 (bs->auth.next_key->conf_key_id);
    }
  else if (!bs->auth.is_delayed && bs->auth.curr_key)
    {
      mp->bfd_key_id = bs->auth.curr_bfd_key_id;
      mp->conf_key_id = clib_host_to_net_u32 (bs->auth.curr_key->conf_key_id);
    }
  ip_address_encode (&key->local_addr, IP46_TYPE_ANY, &mp->local_addr);
  ip_address_encode (&key->peer_addr, IP46_TYPE_ANY, &mp->peer_addr);

  mp->required_min_rx =
    clib_host_to_net_u32 (bs->config_required_min_rx_usec);
  mp->desired_min_tx = clib_host_to_net_u32 (bs->config_desired_min_tx_usec);
  mp->detect_mult = bs->local_detect_mult;
  vl_api_send_msg (reg, (u8 *) mp);
}

void
bfd_event (bfd_main_t * bm, bfd_session_t * bs)
{
  vpe_api_main_t *vam = &vpe_api_main;
  vpe_client_registration_t *reg;
  vl_api_registration_t *vl_reg;
  /* *INDENT-OFF* */
  pool_foreach (reg, vam->bfd_events_registrations, ({
    vl_reg = vl_api_client_index_to_registration (reg->client_index);
    if (vl_reg)
      {
	switch (bs->transport)
	  {
	  case BFD_TRANSPORT_UDP4:
	  /* fallthrough */
	  case BFD_TRANSPORT_UDP6:
	    send_bfd_udp_session_details (vl_reg, 0, bs);
	  }
      }
  }));
  /* *INDENT-ON* */
}

static void
vl_api_bfd_udp_session_dump_t_handler (vl_api_bfd_udp_session_dump_t * mp)
{
  vl_api_registration_t *reg;

  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    return;

  bfd_session_t *bs = NULL;
  /* *INDENT-OFF* */
  pool_foreach (bs, bfd_main.sessions, ({
    if (bs->transport == BFD_TRANSPORT_UDP4 ||
	bs->transport == BFD_TRANSPORT_UDP6)
      send_bfd_udp_session_details (reg, mp->context, bs);
  }));
  /* *INDENT-ON* */
}

static void
vl_api_bfd_udp_session_set_flags_t_handler (vl_api_bfd_udp_session_set_flags_t
					    * mp)
{
  vl_api_bfd_udp_session_set_flags_reply_t *rmp;
  int rv;

  BFD_UDP_API_PARAM_COMMON_CODE;

  rv = bfd_udp_session_set_flags (BFD_UDP_API_PARAM_FROM_MP (mp),
				  clib_net_to_host_u32 (mp->flags) &
				  IF_STATUS_API_FLAG_ADMIN_UP);

  REPLY_MACRO (VL_API_BFD_UDP_SESSION_SET_FLAGS_REPLY);
}

static void
vl_api_bfd_auth_set_key_t_handler (vl_api_bfd_auth_set_key_t * mp)
{
  vl_api_bfd_auth_set_key_reply_t *rmp;
  int rv = bfd_auth_set_key (clib_net_to_host_u32 (mp->conf_key_id),
			     mp->auth_type, mp->key_len, mp->key);

  REPLY_MACRO (VL_API_BFD_AUTH_SET_KEY_REPLY);
}

static void
vl_api_bfd_auth_del_key_t_handler (vl_api_bfd_auth_del_key_t * mp)
{
  vl_api_bfd_auth_del_key_reply_t *rmp;
  int rv = bfd_auth_del_key (clib_net_to_host_u32 (mp->conf_key_id));

  REPLY_MACRO (VL_API_BFD_AUTH_DEL_KEY_REPLY);
}

static void
vl_api_bfd_auth_keys_dump_t_handler (vl_api_bfd_auth_keys_dump_t * mp)
{
  vl_api_registration_t *reg;

  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    return;

  bfd_auth_key_t *key = NULL;
  vl_api_bfd_auth_keys_details_t *rmp = NULL;

  /* *INDENT-OFF* */
  pool_foreach (key, bfd_main.auth_keys, ({
    rmp = vl_msg_api_alloc (sizeof (*rmp));
    clib_memset (rmp, 0, sizeof (*rmp));
    rmp->_vl_msg_id = ntohs (VL_API_BFD_AUTH_KEYS_DETAILS);
    rmp->context = mp->context;
    rmp->conf_key_id = clib_host_to_net_u32 (key->conf_key_id);
    rmp->auth_type = key->auth_type;
    rmp->use_count = clib_host_to_net_u32 (key->use_count);
    vl_api_send_msg (reg, (u8 *)rmp);
  }));
  /* *INDENT-ON* */
}

static void
vl_api_bfd_udp_auth_activate_t_handler (vl_api_bfd_udp_auth_activate_t * mp)
{
  vl_api_bfd_udp_auth_activate_reply_t *rmp;
  int rv;

  VALIDATE_SW_IF_INDEX (mp);

  BFD_UDP_API_PARAM_COMMON_CODE;

  rv = bfd_udp_auth_activate (BFD_UDP_API_PARAM_FROM_MP (mp),
			      clib_net_to_host_u32 (mp->conf_key_id),
			      mp->bfd_key_id, mp->is_delayed);

  BAD_SW_IF_INDEX_LABEL;
  REPLY_MACRO (VL_API_BFD_UDP_AUTH_ACTIVATE_REPLY);
}

static void
vl_api_bfd_udp_auth_deactivate_t_handler (vl_api_bfd_udp_auth_deactivate_t *
					  mp)
{
  vl_api_bfd_udp_auth_deactivate_reply_t *rmp;
  int rv;

  VALIDATE_SW_IF_INDEX (mp);

  BFD_UDP_API_PARAM_COMMON_CODE;

  rv =
    bfd_udp_auth_deactivate (BFD_UDP_API_PARAM_FROM_MP (mp), mp->is_delayed);

  BAD_SW_IF_INDEX_LABEL;
  REPLY_MACRO (VL_API_BFD_UDP_AUTH_DEACTIVATE_REPLY);
}

static void
vl_api_bfd_udp_set_echo_source_t_handler (vl_api_bfd_udp_set_echo_source_t *
					  mp)
{
  vl_api_bfd_udp_set_echo_source_reply_t *rmp;
  int rv;

  VALIDATE_SW_IF_INDEX (mp);

  rv = bfd_udp_set_echo_source (clib_net_to_host_u32 (mp->sw_if_index));

  BAD_SW_IF_INDEX_LABEL;
  REPLY_MACRO (VL_API_BFD_UDP_SET_ECHO_SOURCE_REPLY);
}

static void
vl_api_bfd_udp_del_echo_source_t_handler (vl_api_bfd_udp_del_echo_source_t *
					  mp)
{
  vl_api_bfd_udp_del_echo_source_reply_t *rmp;
  int rv;

  rv = bfd_udp_del_echo_source ();

  REPLY_MACRO (VL_API_BFD_UDP_DEL_ECHO_SOURCE_REPLY);
}

static void
vl_api_bfd_udp_get_echo_source_t_handler (vl_api_bfd_udp_get_echo_source_t *
					  mp)
{
  vl_api_bfd_udp_get_echo_source_reply_t *rmp;
  int rv = 0;
  int is_set;
  u32 sw_if_index;
  int have_usable_ip4;
  ip4_address_t ip4;
  int have_usable_ip6;
  ip6_address_t ip6;

  bfd_udp_get_echo_source (&is_set, &sw_if_index, &have_usable_ip4, &ip4,
			   &have_usable_ip6, &ip6);

  /* *INDENT-OFF* */
  REPLY_MACRO2 (VL_API_BFD_UDP_GET_ECHO_SOURCE_REPLY,
  ({
    rmp->sw_if_index = ntohl (sw_if_index);
    if (is_set)
      {
        rmp->is_set = true;
        rmp->sw_if_index = clib_host_to_net_u32 (sw_if_index);
        if (have_usable_ip4)
          {
            rmp->have_usable_ip4 = true;
	    ip4_address_encode(&ip4, rmp->ip4_addr);
          }
        else
          {
            rmp->have_usable_ip4 = false;
          }
        if (have_usable_ip6)
          {
            rmp->have_usable_ip6 = true;
	    ip6_address_encode(&ip6, rmp->ip6_addr);
          }
        else
          {
            rmp->have_usable_ip6 = false;
          }
      }
    else
      {
        rmp->is_set = false;
        rmp->have_usable_ip4 = false;
        rmp->have_usable_ip6 = false;
      }
  }))
  /* *INDENT-ON* */
}

/*
 * bfd_api_hookup
 * Add vpe's API message handlers to the table.
 * vlib has already mapped shared memory and
 * added the client registration handlers.
 * See .../vlib-api/vlibmemory/memclnt_vlib.c:memclnt_process()
 */
#define vl_msg_name_crc_list
#include <vnet/vnet_all_api_h.h>
#undef vl_msg_name_crc_list

static void
setup_message_id_table (api_main_t * am)
{
#define _(id, n, crc) vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id);
  foreach_vl_msg_name_crc_bfd;
#undef _
}

static clib_error_t *
bfd_api_hookup (vlib_main_t * vm)
{
  api_main_t *am = &api_main;

#define _(N, n)                                                    \
  vl_msg_api_set_handlers (VL_API_##N, #n, vl_api_##n##_t_handler, \
                           vl_noop_handler, vl_api_##n##_t_endian, \
                           vl_api_##n##_t_print, sizeof (vl_api_##n##_t), 1);
  foreach_vpe_api_msg;
#undef _

  /*
   * Set up the (msg_name, crc, message-id) table
   */
  setup_message_id_table (am);

  return 0;
}

VLIB_API_INIT_FUNCTION (bfd_api_hookup);

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
# 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 r = VppIpRoute(self, "127.0.0.0", 8, [VppRoutePath("127.0.0.1", lo.sw_if_index)]).add_vpp_config() r.remove_vpp_config() r.add_vpp_config() # remove the default route r.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()) if __name__ == '__main__': unittest.main(testRunner=VppTestRunner)