import os import socket from socket import inet_pton, inet_ntop import struct import time from traceback import format_exc, format_stack from config import config import scapy.compat from scapy.utils import wrpcap, rdpcap, PcapReader from scapy.plist import PacketList from vpp_interface import VppInterface from vpp_papi import VppEnum from scapy.layers.l2 import Ether, ARP from scapy.layers.inet6 import ( IPv6, ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, IPv6ExtHdrHopByHop, ) from util import ppp, ppc, UnexpectedPacketError from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr class CaptureTimeoutError(Exception): """Exception raised if capture or packet doesn't appear within timeout""" pass def is_ipv6_misc(p): """Is packet one of uninteresting IPv6 broadcasts?""" if p.haslayer(ICMPv6ND_RA): if in6_ismaddr(p[IPv6].dst): return True if p.haslayer(IPv6ExtHdrHopByHop): for o in p[IPv6ExtHdrHopByHop].options: if isinstance(o, RouterAlert): return True return False class VppPGInterface(VppInterface): """ VPP packet-generator interface """ @property def pg_index(self): """packet-generator interface index assigned by VPP""" return self._pg_index @property def gso_enabled(self): """gso enabled on packet-generator interface""" if self._gso_enabled == 0: return "gso-disabled" return "gso-enabled" @property def gso_size(self): """gso size on packet-generator interface""" return self._gso_size @property def coalesce_is_enabled(self): """coalesce enabled on packet-generator interface""" if self._coalesce_enabled == 0: return "coalesce-disabled" return "coalesce-enabled" @property def out_path(self): """pcap file path - captured packets""" return self._out_path def get_in_path(self, worker): """pcap file path - injected packets""" if worker is not None: return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index, worker) return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index) @property def capture_cli(self): """CLI string to start capture on this interface""" return self._capture_cli def get_cap_name(self, worker=None): """return capture name for this interface and given worker""" if worker is not None: return self._cap_name + "-worker%d" % worker return self._cap_name def get_input_cli(self, nb_replays=None, worker=None): """return CLI string to load the injected packets""" input_cli = "packet-generator new pcap %s source pg%u name %s" % ( self.get_in_path(worker), self.pg_index, self.get_cap_name(worker), ) if nb_replays is not None: return "%s limit %d" % (input_cli, nb_replays) if worker is not None: return "%s worker %d" % (input_cli, worker) return input_cli @property def in_history_counter(self): """Self-incrementing counter used when renaming old pcap files""" v = self._in_history_counter self._in_history_counter += 1 return v @property def out_history_counter(self): """Self-incrementing counter used when renaming old pcap files""" v = self._out_history_counter self._out_history_counter += 1 return v def __init__(self, test, pg_index, gso, gso_size, mode): """Create VPP packet-generator interface""" super().__init__(test) r = test.vapi.pg_create_interface_v2(pg_index, gso, gso_size, mode) self.set_sw_if_index(r.sw_if_index) self._in_history_counter = 0 self._out_history_counter = 0 self._out_assert_counter = 0 self._pg_index = pg_index self._gso_enabled = gso self._gso_size = gso_size self._coalesce_enabled = 0 self._out_file = "pg%u_out.pcap" % self.pg_index self._out_path = self.test.tempdir + "/" + self._out_file self._capture_cli = "packet-generator capture pg%u pcap %s" % ( self.pg_index, self.out_path, ) self._cap_name = "pcap%u-sw_if_index-%s" % (self.pg_index, self.sw_if_index) def handle_old_pcap_file(self, path, counter): filename = os.path.basename(path) if not config.keep_pcaps: try: self.test.logger.debug(f"Removing {path}") os.remove(path) except OSError: self.test.logger.debug(f"OSError: Could not remove {path}") return # keep try: if os.path.isfile(path): name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % ( self.test.tempdir, time.time(), self.name, counter, filename, ) self.test.logger.debug("Renaming %s->%s" % (path, name)) os.rename(path, name) except OSError: self.test.logger.debug("OSError: Could not rename %s %s" % (path, filename)) def enable_capture(self): """Enable capture on this packet-generator interface of at most n packets. If n < 0, this is no limit """ # disable the capture to flush the capture self.disable_capture() self.handle_old_pcap_file(self.out_path, self.out_history_counter) # FIXME this should be an API, but no such exists atm self.test.vapi.cli(self.capture_cli) self._pcap_reader = None def disable_capture(self): self.test.vapi.cli("%s disable" % self.capture_cli) def coalesce_enable(self): """Enable packet coalesce on this packet-generator interface""" self._coalesce_enabled = 1 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 1) def coalesce_disable(self): """Disable packet coalesce on this packet-generator interface""" self._coalesce_enabled = 0 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 0) def add_stream(self, pkts, nb_replays=None, worker=None): """ Add a stream of packets to this packet-generator :param pkts: iterable packets """ wrpcap(self.get_in_path(worker), pkts) self.test.register_pcap(self, worker) # FIXME this should be an API, but no such exists atm self.test.vapi.cli(self.get_input_cli(nb_replays, worker)) def generate_debug_aid(self, kind): """Create a hardlink to the out file with a counter and a file containing stack trace to ease debugging in case of multiple capture files present.""" self.test.logger.debug("Generating debug aid for %s on %s" % (kind, self._name)) link_path, stack_path = [ "%s/debug_%s_%s_%s.%s" % (self.test.tempdir, self._name, self._out_assert_counter, kind, suffix) for suffix in ["pcap", "stack"] ] os.link(self.out_path, link_path) with open(stack_path, "w") as f: f.writelines(format_stack()) self._out_assert_counter += 1 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc): """Helper method to get capture and filter it""" try: if not self.wait_for_capture_file(timeout): return None output = rdpcap(self.out_path) self.test.logger.debug("Capture has %s packets" % len(output.res)) except: self.test.logger.debug( "Exception in scapy.rdpcap (%s): %s" % (self.out_path, format_exc()) ) return None before = len(output.res) if filter_out_fn: output.res = [p for p in output.res if not filter_out_fn(p)] removed = before - len(output.res) if removed: self.test.logger.debug( "Filtered out %s packets from capture (returning %s)" % (removed, len(output.res)) ) return output def get_capture( self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc ): """Get captured packets :param expected_count: expected number of packets to capture, if None, then self.test.packet_count_for_dst_pg_idx is used to lookup the expected count :param remark: remark printed into debug logs :param timeout: how long to wait for packets :param filter_out_fn: filter applied to each packet, packets for which the filter returns True are removed from capture :returns: iterable packets """ remaining_time = timeout capture = None name = self.name if remark is None else "%s (%s)" % (self.name, remark) based_on = "based on provided argument" if expected_count is None: expected_count = self.test.get_packet_count_for_if_idx(self.sw_if_index) based_on = "based on stored packet_infos" if expected_count == 0: raise Exception( "Internal error, expected packet count for %s is 0!" % name ) self.test.logger.debug( "Expecting to capture %s (%s) packets on %s" % (expected_count, based_on, name) ) while remaining_time > 0: before = time.time() capture = self._get_capture(remaining_time, filter_out_fn) elapsed_time = time.time() - before if capture: if len(capture.res) == expected_count: # bingo, got the packets we expected return capture elif len(capture.res) > expected_count: self.test.logger.error(ppc("Unexpected packets captured:", capture)) break else: self.test.logger.debug( "Partial capture containing %s " "packets doesn't match expected " "count %s (yet?)" % (len(capture.res), expected_coun
/*
 * 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.
 */
/**
 * @brief
 * The data-path object representing receiveing the packet, i.e. it's for-us
 */
#include <vlib/vlib.h>
#include <vnet/ip/ip.h>
#include <vnet/dpo/receive_dpo.h>

/**
 * @brief pool of all receive DPOs
 */
receive_dpo_t *receive_dpo_pool;

int
dpo_is_receive (const dpo_id_t *dpo)
{
    return (dpo->dpoi_type == DPO_RECEIVE);
}

static receive_dpo_t *
receive_dpo_alloc