#!/usr/bin/env python3 import six import unittest from random import shuffle, choice, randrange from framework import VppTestCase, VppTestRunner import scapy.compat from scapy.packet import Raw from scapy.layers.l2 import Ether, GRE from scapy.layers.inet import IP, UDP, ICMP from scapy.layers.inet6 import HBHOptUnknown, ICMPv6ParamProblem,\ ICMPv6TimeExceeded, IPv6, IPv6ExtHdrFragment, IPv6ExtHdrHopByHop from framework import VppTestCase, VppTestRunner from util import ppp, ppc, fragment_rfc791, fragment_rfc8200 from vpp_gre_interface import VppGreInterface from vpp_ip import DpoProto from vpp_ip_route import VppIpRoute, VppRoutePath, FibPathProto from vpp_papi import VppEnum # 35 is enough to have >257 400-byte fragments test_packet_count = 35 # number of workers used for multi-worker test cases worker_count = 3 class TestIPv4Reassembly(VppTestCase): """ IPv4 Reassembly """ @classmethod def setUpClass(cls): super(TestIPv4Reassembly, 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() # packet sizes cls.packet_sizes = [64, 512, 1518, 9018] cls.padding = " abcdefghijklmn" cls.create_stream(cls.packet_sizes) cls.create_fragments() @classmethod def tearDownClass(cls): super(TestIPv4Reassembly, cls).tearDownClass() def setUp(self): """ Test setup - force timeout on existing reassemblies """ super(TestIPv4Reassembly, self).setUp() self.vapi.ip_reassembly_enable_disable( sw_if_index=self.src_if.sw_if_index, enable_ip4=True) self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=10) self.sleep(.25) self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=10000) def tearDown(self): super(TestIPv4Reassembly, self).tearDown() def show_commands_at_teardown(self): self.logger.debug(self.vapi.ppcli("show ip4-full-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) @classmethod def create_stream(cls, packet_sizes, packet_count=test_packet_count): """Create input packet stream :param list packet_sizes: Required packet sizes. """ for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) p = (Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) / IP(id=info.index, src=cls.src_if.remote_ip4, dst=cls.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(payload)) size = packet_sizes[(i // 2) % len(packet_sizes)] cls.extend_packet(p, size, cls.padding) info.data = p @classmethod def create_fragments(cls): infos = cls._packet_infos cls.pkt_infos = [] for index, info in six.iteritems(infos): p = info.data # cls.logger.debug(ppp("Packet:", # p.__class__(scapy.compat.raw(p)))) fragments_400 = fragment_rfc791(p, 400) fragments_300 = fragment_rfc791(p, 300) fragments_200 = [ x for f in fragments_400 for x in fragment_rfc791(f, 200)] cls.pkt_infos.append( (index, fragments_400, fragments_300, fragments_200)) cls.fragments_400 = [ x for (_, frags, _, _) in cls.pkt_infos for x in frags] cls.fragments_300 = [ x for (_, _, frags, _) in cls.pkt_infos for x in frags] cls.fragments_200 = [ x for (_, _, _, frags) in cls.pkt_infos for x in frags] cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " "%s 300-byte fragments and %s 200-byte fragments" % (len(infos), len(cls.fragments_400), len(cls.fragments_300), len(cls.fragments_200))) def verify_capture(self, capture, dropped_packet_indexes=[]): """Verify captured packet stream. :param list capture: Captured packet stream. """ info = None seen = set() for packet in capture: try: self.logger.debug(ppp("Got packet:", packet)) ip = packet[IP] udp = packet[UDP] payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, ppp("Packet received, but should be dropped:", packet)) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) self.assertEqual(payload_info.dst, self.src_if.sw_if_index) info = self._packet_infos[packet_index] self.assertTrue(info is not None) self.assertEqual(packet_index, info.index) saved_packet = info.data self.assertEqual(ip.src, saved_packet[IP].src) self.assertEqual(ip.dst, saved_packet[IP].dst) self.assertEqual(udp.payload, saved_packet[UDP].payload) except Exception: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: self.assertTrue(index in seen or index in dropped_packet_indexes, "Packet with packet_index %d not received" % index) def test_reassembly(self): """ basic reassembly """ self.pg_enable_capture() self.src_if.add_stream(self.fragments_200) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all again to verify correctness self.pg_enable_capture() self.src_if.add_stream(self.fragments_200) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_reversed(self): """ reverse order reassembly """ fragments = list(self.fragments_200) fragments.reverse() self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.packet_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all again to verify correctness self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.packet_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_long_fragment_chain(self): """ long fragment chain """ error_cnt_str = \ "/err/ip4-full-reassembly-feature/fragment chain too long (drop)" error_cnt = self.statistics.get_err_counter(error_cnt_str) self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, max_reassembly_length=3, expire_walk_interval_ms=50) p1 = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(b"X" * 1000)) p2 = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=1001, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(b"X" * 1000)) frags = fragment_rfc791(p1, 200) + fragment_rfc791(p2, 500) self.pg_enable_capture() self.src_if.add_stream(frags) self.pg_start() self.dst_if.get_capture(1) self.assert_error_counter_equal(error_cnt_str, error_cnt + 1) def test_5737(self): """ fragment length + ip header size > 65535 """ self.vapi.cli("clear errors") raw = b'''E\x00\x00\x88,\xf8\x1f\xfe@\x01\x98\x00\xc0\xa8\n-\xc0\xa8\n\ \x01\x08\x00\xf0J\xed\xcb\xf1\xf5Test-group: IPv4.IPv4.ipv4-message.\ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' malformed_packet = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(raw)) p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(b"X" * 1000)) valid_fragments = fragment_rfc791(p, 400) counter = "/err/ip4-full-reassembly-feature/malformed packets" error_counter = self.statistics.get_err_counter(counter) self.pg_enable_capture() self.src_if.add_stream([malformed_packet] + valid_fragments) self.pg_start() self.dst_if.get_capture(1) self.logger.debug(self.vapi.ppcli("show error")) self.assertEqual(self.statistics.get_err_counter(counter), error_counter + 1) def test_44924(self): """ compress tiny fragments """ packets = [(Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=24339, flags="MF", frag=0, ttl=64, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) / Raw(load='Test-group: IPv4')), (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=24339, flags="MF", frag=3, ttl=64, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) / Raw(load='.IPv4.Fragmentation.vali')), (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=24339, frag=6, ttl=64, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) / Raw(load='d; Test-case: 44924')) ] self.pg_enable_capture() self.src_if.add_stream(packets) self.pg_start() self.dst_if.get_capture(1) def test_frag_1(self): """ fragment of size 1 """ self.vapi.cli("clear errors") malformed_packets = [(Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=7, len=21, flags="MF", frag=0, ttl=64, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / ICMP(type="echo-request")), (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=7, len=21, frag=1, ttl=64, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / Raw(load=b'\x08')), ] p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(b"X" * 1000)) valid_fragments = fragment_rfc791(p, 400) self.pg_enable_capture() self.src_if.add_stream(malformed_packets + valid_fragments) self.pg_start() self.dst_if.get_capture(1) self.assert_packet_counter_equal("ip4-full-reassembly-feature", 1) # TODO remove above, uncomment below once clearing of counters # is supported # self.assert_packet_counter_equal( # "/err/ip4-full-reassembly-feature/malformed packets", 1) def test_random(self): """ random order reassembly """ fragments = list(self.fragments_200) shuffle(fragments) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.packet_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all again to verify correctness self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.packet_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_duplicates(self): """ duplicate fragments """ fragments = [ x for (_, frags, _, _) in self.pkt_infos for x in frags for _ in range(0, min(2, len(frags))) ] self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_overlap1(self): """ overlapping fragments case #1 """ fragments = [] for _, _, frags_300, frags_200 in self.pkt_infos: if len(frags_300) == 1: fragments.extend(frags_300) else: for i, j in zip(frags_200, frags_300): fragments.extend(i) fragments.extend(j) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all to verify correctness self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_overlap2(self): """ overlapping fragments case #2 """ fragments = [] for _, _, frags_300, frags_200 in self.pkt_infos: if len(frags_300) == 1: fragments.extend(frags_300) else: # care must be taken here so that there are no fragments # received by vpp after reassembly is finished, otherwise # new reassemblies will be started and packet generator will # freak out when it detects unfreed buffers zipped = zip(frags_300, frags_200) for i, j in zipped: fragments.extend(i) fragments.extend(j) fragments.pop() self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all to verify correctness self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_timeout_inline(self): """ timeout (inline) """ dropped_packet_indexes = set( index for (index, frags, _, _) in self.pkt_infos if len(frags) > 1 ) self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, max_reassembly_length=3, expire_walk_interval_ms=10000) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_timeout_cleanup(self): """ timeout (cleanup) """ # whole packets + fragmented packets sans last fragment fragments = [ x for (_, frags_400, _, _) in self.pkt_infos for x in frags_400[:-1 if len(frags_400) > 1 else None] ] # last fragments for fragmented packets fragments2 = [frags_400[-1] for (_, frags_400, _, _) in self.pkt_infos if len(frags_400) > 1] dropped_packet_indexes = set( index for (index, frags_400, _, _) in self.pkt_infos if len(frags_400) > 1) self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=50) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() self.sleep(.25, "wait before sending rest of fragments") self.src_if.add_stream(fragments2) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_disabled(self): """ reassembly disabled """ dropped_packet_indexes = set( index for (index, frags_400, _, _) in self.pkt_infos if len(frags_400) > 1) self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=0, max_reassembly_length=3, expire_walk_interval_ms=10000) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() class TestIPv4SVReassembly(VppTestCase): """ IPv4 Shallow Virtual Reassembly """ @classmethod def setUpClass(cls): super(TestIPv4SVReassembly, 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() def setUp(self): """ Test setup - force timeout on existing reassemblies """ super(TestIPv4SVReassembly, self).setUp() self.vapi.ip_reassembly_enable_disable( sw_if_index=self.src_if.sw_if_index, enable_ip4=True, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL) self.vapi.ip_reassembly_set( timeout_ms=0, max_reassemblies=1000, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, expire_walk_interval_ms=10) self.sleep(.25) self.vapi.ip_reassembly_set( timeout_ms=1000000, max_reassemblies=1000, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, expire_walk_interval_ms=10000) def tearDown(self): super(TestIPv4SVReassembly, self).tearDown() self.logger.debug(self.vapi.ppcli("show ip4-sv-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) def test_basic(self): """ basic reassembly """ payload_len = 1000 payload = "" counter = 0 while len(payload) < payload_len: payload += "%u " % counter counter += 1 p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(payload)) fragments = fragment_rfc791(p, payload_len/4) # send fragment #2 - should be cached inside reassembly self.pg_enable_capture() self.src_if.add_stream(fragments[1]) self.pg_start() self.logger.debug(self.vapi.ppcli("show ip4-sv-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) self.logger.debug(self.vapi.ppcli("show trace")) self.dst_if.assert_nothing_captured() # send fragment #1 - reassembly is finished now and both fragments # forwarded self.pg_enable_capture() self.src_if.add_stream(fragments[0]) self.pg_start() self.logger.debug(self.vapi.ppcli("show ip4-sv-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) self.logger.debug(self.vapi.ppcli("show trace")) c = self.dst_if.get_capture(2) for sent, recvd in zip([fragments[1], fragments[0]], c): self.assertEqual(sent[IP].src, recvd[IP].src) self.assertEqual(sent[IP].dst, recvd[IP].dst) self.assertEqual(sent[Raw].payload, recvd[Raw].payload) # send rest of fragments - should be immediately forwarded self.pg_enable_capture() self.src_if.add_stream(fragments[2:]) self.pg_start() c = self.dst_if.get_capture(len(fragments[2:])) for sent, recvd in zip(fragments[2:], c): self.assertEqual(sent[IP].src, recvd[IP].src) self.assertEqual(sent[IP].dst, recvd[IP].dst) self.assertEqual(sent[Raw].payload, recvd[Raw].payload) def test_timeout(self): """ reassembly timeout """ payload_len = 1000 payload = "" counter = 0 while len(payload) < payload_len: payload += "%u " % counter counter += 1 p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(payload)) fragments = fragment_rfc791(p, payload_len/4) self.vapi.ip_reassembly_set( timeout_ms=100, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=50, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL) # send fragments #2 and #1 - should be forwarded self.pg_enable_capture() self.src_if.add_stream(fragments[0:2]) self.pg_start() self.logger.debug(self.vapi.ppcli("show ip4-sv-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) self.logger.debug(self.vapi.ppcli("show trace")) c = self.dst_if.get_capture(2) for sent, recvd in zip([fragments[1], fragments[0]], c): self.assertEqual(sent[IP].src, recvd[IP].src) self.assertEqual(sent[IP].dst, recvd[IP].dst) self.assertEqual(sent[Raw].payload, recvd[Raw].payload) # wait for cleanup self.sleep(.25, "wait before sending rest of fragments") # send rest of fragments - shouldn't be forwarded self.pg_enable_capture() self.src_if.add_stream(fragments[2:]) self.pg_start() self.dst_if.assert_nothing_captured() def test_lru(self): """ reassembly reuses LRU element """ self.vapi.ip_reassembly_set( timeout_ms=1000000, max_reassemblies=1, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, expire_walk_interval_ms=10000) payload_len = 1000 payload = "" counter = 0 while len(payload) < payload_len: payload += "%u " % counter counter += 1 packet_count = 10 fragments = [f for i in range(packet_count) for p in (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=i, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(payload)) for f in fragment_rfc791(p, payload_len/4)] self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() c = self.dst_if.get_capture(len(fragments)) for sent, recvd in zip(fragments, c): self.assertEqual(sent[IP].src, recvd[IP].src) self.assertEqual(sent[IP].dst, recvd[IP].dst) self.assertEqual(sent[Raw].payload, recvd[Raw].payload) def send_mixed_and_verify_capture(self, traffic): stream = [] for t in traffic: for c in range(t['count']): stream.append( (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IP(id=self.counter, flags=t['flags'], src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw("abcdef"))) self.counter = self.counter + 1 self.pg_enable_capture() self.src_if.add_stream(stream) self.pg_start() self.logger.debug(self.vapi.ppcli("show ip4-sv-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) self.logger.debug(self.vapi.ppcli("show trace")) self.dst_if.get_capture(len(stream)) def test_mixed(self): """ mixed traffic correctly passes through SVR """ self.counter = 1 self.send_mixed_and_verify_capture([{'count': 1, 'flags': ''}]) self.send_mixed_and_verify_capture([{'count': 2, 'flags': ''}]) self.send_mixed_and_verify_capture([{'count': 3, 'flags': ''}]) self.send_mixed_and_verify_capture([{'count': 8, 'flags': ''}]) self.send_mixed_and_verify_capture([{'count': 257, 'flags': ''}]) self.send_mixed_and_verify_capture([{'count': 1, 'flags': 'MF'}]) self.send_mixed_and_verify_capture([{'count': 2, 'flags': 'MF'}]) self.send_mixed_and_verify_capture([{'count': 3, 'flags': 'MF'}]) self.send_mixed_and_verify_capture([{'count': 8, 'flags': 'MF'}]) self.send_mixed_and_verify_capture([{'count': 257, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 129, 'flags': ''}, {'count': 129, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}, {'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}, {'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}, {'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}, {'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}]) self.send_mixed_and_verify_capture( [{'count': 65, 'flags': ''}, {'count': 65, 'flags': 'MF'}, {'count': 65, 'flags': ''}, {'count': 65, 'flags': 'MF'}]) class TestIPv4MWReassembly(VppTestCase): """ IPv4 Reassembly (multiple workers) """ worker_config = "workers %d" % worker_count @classmethod def setUpClass(cls): super(TestIPv4MWReassembly, cls).setUpClass() cls.create_pg_interfaces(range(worker_count+1)) cls.src_if = cls.pg0 cls.send_ifs = cls.pg_interfaces[:-1] cls.dst_if = cls.pg_interfaces[-1] # setup all interfaces for i in cls.pg_interfaces: i.admin_up() i.config_ip4() i.resolve_arp() # packets sizes reduced here because we are generating packets without # Ethernet headers, which are added later (diff fragments go via # different interfaces) cls.packet_sizes = [64-len(Ether()), 512-len(Ether()), 1518-len(Ether()), 9018-len(Ether())] cls.padding = " abcdefghijklmn" cls.create_stream(cls.packet_sizes) cls.create_fragments() @classmethod def tearDownClass(cls): super(TestIPv4MWReassembly, cls).tearDownClass() def setUp(self): """ Test setup - force timeout on existing reassemblies """ super(TestIPv4MWReassembly, self).setUp() for intf in self.send_ifs: self.vapi.ip_reassembly_enable_disable( sw_if_index=intf.sw_if_index, enable_ip4=True) self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=10) self.sleep(.25) self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=10000) def tearDown(self): super(TestIPv4MWReassembly, self).tearDown() def show_commands_at_teardown(self): self.logger.debug(self.vapi.ppcli("show ip4-full-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) @classmethod def create_stream(cls, packet_sizes, packet_count=test_packet_count): """Create input packet stream :param list packet_sizes: Required packet sizes. """ for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) p = (IP(id=info.index, src=cls.src_if.remote_ip4, dst=cls.dst_if.remote_ip4) / UDP(sport=1234, dport=5678) / Raw(payload)) size = packet_sizes[(i // 2) % len(packet_sizes)] cls.extend_packet(p, size, cls.padding) info.data = p @classmethod def create_fragments(cls): infos = cls._packet_infos cls.pkt_infos = [] for index, info in six.iteritems(infos): p = info.data # cls.logger.debug(ppp("Packet:", # p.__class__(scapy.compat.raw(p)))) fragments_400 = fragment_rfc791(p, 400) cls.pkt_infos.append((index, fragments_400)) cls.fragments_400 = [ x for (_, frags) in cls.pkt_infos for x in frags] cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " % (len(infos), len(cls.fragments_400))) def verify_capture(self, capture, dropped_packet_indexes=[]): """Verify captured packet stream. :param list capture: Captured packet stream. """ info = None seen = set() for packet in capture: try: self.logger.debug(ppp("Got packet:", packet)) ip = packet[IP] udp = packet[UDP] payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, ppp("Packet received, but should be dropped:", packet)) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) self.assertEqual(payload_info.dst, self.src_if.sw_if_index) info = self._packet_infos[packet_index] self.assertTrue(info is not None) self.assertEqual(packet_index, info.index) saved_packet = info.data self.assertEqual(ip.src, saved_packet[IP].src) self.assertEqual(ip.dst, saved_packet[IP].dst) self.assertEqual(udp.payload, saved_packet[UDP].payload) except Exception: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: self.assertTrue(index in seen or index in dropped_packet_indexes, "Packet with packet_index %d not received" % index) def send_packets(self, packets): for counter in range(worker_count): if 0 == len(packets[counter]): continue send_if = self.send_ifs[counter] send_if.add_stream( (Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x for x in packets[counter]), worker=counter) self.pg_start() def test_worker_conflict(self): """ 1st and FO=0 fragments on different workers """ # in first wave we send fragments which don't start at offset 0 # then we send fragments with offset 0 on a different thread # then the rest of packets on a random thread first_packets = [[] for n in range(worker_count)] second_packets = [[] for n in range(worker_count)] rest_of_packets = [[] for n in range(worker_count)] for (_, p) in self.pkt_infos: wi = randrange(worker_count) second_packets[wi].append(p[0]) if len(p) <= 1: continue wi2 = wi while wi2 == wi: wi2 = randrange(worker_count) first_packets[wi2].append(p[1]) wi3 = randrange(worker_count) rest_of_packets[wi3].extend(p[2:]) self.pg_enable_capture() self.send_packets(first_packets) self.send_packets(second_packets) self.send_packets(rest_of_packets) packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) for send_if in self.send_ifs: send_if.assert_nothing_captured() self.logger.debug(self.vapi.ppcli("show trace")) self.logger.debug(self.vapi.ppcli("show ip4-full-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) self.vapi.cli("clear trace") self.pg_enable_capture() self.send_packets(first_packets) self.send_packets(second_packets) self.send_packets(rest_of_packets) packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) for send_if in self.send_ifs: send_if.assert_nothing_captured() class TestIPv6Reassembly(VppTestCase): """ IPv6 Reassembly """ @classmethod def setUpClass(cls): super(TestIPv6Reassembly, 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_ip6() i.resolve_ndp() # packet sizes cls.packet_sizes = [64, 512, 1518, 9018] cls.padding = " abcdefghijklmn" cls.create_stream(cls.packet_sizes) cls.create_fragments() @classmethod def tearDownClass(cls): super(TestIPv6Reassembly, cls).tearDownClass() def setUp(self): """ Test setup - force timeout on existing reassemblies """ super(TestIPv6Reassembly, self).setUp() self.vapi.ip_reassembly_enable_disable( sw_if_index=self.src_if.sw_if_index, enable_ip6=True) self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=10, is_ip6=1) self.sleep(.25) self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=10000, is_ip6=1) self.logger.debug(self.vapi.ppcli("show ip6-full-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) def tearDown(self): super(TestIPv6Reassembly, self).tearDown() def show_commands_at_teardown(self): self.logger.debug(self.vapi.ppcli("show ip6-full-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) @classmethod def create_stream(cls, packet_sizes, packet_count=test_packet_count): """Create input packet stream for defined interface. :param list packet_sizes: Required packet sizes. """ for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) p = (Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) / IPv6(src=cls.src_if.remote_ip6, dst=cls.dst_if.remote_ip6) / UDP(sport=1234, dport=5678) / Raw(payload)) size = packet_sizes[(i // 2) % len(packet_sizes)] cls.extend_packet(p, size, cls.padding) info.data = p @classmethod def create_fragments(cls): infos = cls._packet_infos cls.pkt_infos = [] for index, info in six.iteritems(infos): p = info.data # cls.logger.debug(ppp("Packet:", # p.__class__(scapy.compat.raw(p)))) fragments_400 = fragment_rfc8200(p, info.index, 400) fragments_300 = fragment_rfc8200(p, info.index, 300) cls.pkt_infos.append((index, fragments_400, fragments_300)) cls.fragments_400 = [ x for _, frags, _ in cls.pkt_infos for x in frags] cls.fragments_300 = [ x for _, _, frags in cls.pkt_infos for x in frags] cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " "and %s 300-byte fragments" % (len(infos), len(cls.fragments_400), len(cls.fragments_300))) def verify_capture(self, capture, dropped_packet_indexes=[]): """Verify captured packet strea . :param list capture: Captured packet stream. """ info = None seen = set() for packet in capture: try: self.logger.debug(ppp("Got packet:", packet)) ip = packet[IPv6] udp = packet[UDP] payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, ppp("Packet received, but should be dropped:", packet)) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) self.assertEqual(payload_info.dst, self.src_if.sw_if_index) info = self._packet_infos[packet_index] self.assertTrue(info is not None) self.assertEqual(packet_index, info.index) saved_packet = info.data self.assertEqual(ip.src, saved_packet[IPv6].src) self.assertEqual(ip.dst, saved_packet[IPv6].dst) self.assertEqual(udp.payload, saved_packet[UDP].payload) except Exception: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: self.assertTrue(index in seen or index in dropped_packet_indexes, "Packet with packet_index %d not received" % index) def test_reassembly(self): """ basic reassembly """ self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all again to verify correctness self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_buffer_boundary(self): """ fragment header crossing buffer boundary """ p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) / IPv6ExtHdrHopByHop( options=[HBHOptUnknown(otype=0xff, optlen=0)] * 1000) / IPv6ExtHdrFragment(m=1) / UDP(sport=1234, dport=5678) / Raw()) self.pg_enable_capture() self.src_if.add_stream([p]) self.pg_start() self.src_if.assert_nothing_captured() self.dst_if.assert_nothing_captured() def test_reversed(self): """ reverse order reassembly """ fragments = list(self.fragments_400) fragments.reverse() self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all again to verify correctness self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_random(self): """ random order reassembly """ fragments = list(self.fragments_400) shuffle(fragments) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() # run it all again to verify correctness self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_duplicates(self): """ duplicate fragments """ fragments = [ x for (_, frags, _) in self.pkt_infos for x in frags for _ in range(0, min(2, len(frags))) ] self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture(len(self.pkt_infos)) self.verify_capture(packets) self.src_if.assert_nothing_captured() def test_long_fragment_chain(self): """ long fragment chain """ error_cnt_str = \ "/err/ip6-full-reassembly-feature/fragment chain too long (drop)" error_cnt = self.statistics.get_err_counter(error_cnt_str) self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, max_reassembly_length=3, expire_walk_interval_ms=50, is_ip6=1) p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / UDP(sport=1234, dport=5678) / Raw(b"X" * 1000)) frags = fragment_rfc8200(p, 1, 300) + fragment_rfc8200(p, 2, 500) self.pg_enable_capture() self.src_if.add_stream(frags) self.pg_start() self.dst_if.get_capture(1) self.assert_error_counter_equal(error_cnt_str, error_cnt + 1) def test_overlap1(self): """ overlapping fragments case #1 """ fragments = [] for _, frags_400, frags_300 in self.pkt_infos: if len(frags_300) == 1: fragments.extend(frags_400) else: for i, j in zip(frags_300, frags_400): fragments.extend(i) fragments.extend(j) dropped_packet_indexes = set( index for (index, _, frags) in self.pkt_infos if len(frags) > 1 ) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_overlap2(self): """ overlapping fragments case #2 """ fragments = [] for _, frags_400, frags_300 in self.pkt_infos: if len(frags_400) == 1: fragments.extend(frags_400) else: # care must be taken here so that there are no fragments # received by vpp after reassembly is finished, otherwise # new reassemblies will be started and packet generator will # freak out when it detects unfreed buffers zipped = zip(frags_400, frags_300) for i, j in zipped: fragments.extend(i) fragments.extend(j) fragments.pop() dropped_packet_indexes = set( index for (index, _, frags) in self.pkt_infos if len(frags) > 1 ) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_timeout_inline(self): """ timeout (inline) """ dropped_packet_indexes = set( index for (index, frags, _) in self.pkt_infos if len(frags) > 1 ) self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, max_reassembly_length=3, expire_walk_interval_ms=10000, is_ip6=1) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) pkts = self.src_if.get_capture( expected_count=len(dropped_packet_indexes)) for icmp in pkts: self.assertIn(ICMPv6TimeExceeded, icmp) self.assertIn(IPv6ExtHdrFragment, icmp) self.assertIn(icmp[IPv6ExtHdrFragment].id, dropped_packet_indexes) dropped_packet_indexes.remove(icmp[IPv6ExtHdrFragment].id) def test_timeout_cleanup(self): """ timeout (cleanup) """ # whole packets + fragmented packets sans last fragment fragments = [ x for (_, frags_400, _) in self.pkt_infos for x in frags_400[:-1 if len(frags_400) > 1 else None] ] # last fragments for fragmented packets fragments2 = [frags_400[-1] for (_, frags_400, _) in self.pkt_infos if len(frags_400) > 1] dropped_packet_indexes = set( index for (index, frags_400, _) in self.pkt_infos if len(frags_400) > 1) self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=50) self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=50, is_ip6=1) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() self.sleep(.25, "wait before sending rest of fragments") self.src_if.add_stream(fragments2) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) pkts = self.src_if.get_capture( expected_count=len(dropped_packet_indexes)) for icmp in pkts: self.assertIn(ICMPv6TimeExceeded, icmp) self.assertIn(IPv6ExtHdrFragment, icmp) self.assertIn(icmp[IPv6ExtHdrFragment].id, dropped_packet_indexes) dropped_packet_indexes.remove(icmp[IPv6ExtHdrFragment].id) def test_disabled(self): """ reassembly disabled """ dropped_packet_indexes = set( index for (index, frags_400, _) in self.pkt_infos if len(frags_400) > 1) self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=0, max_reassembly_length=3, expire_walk_interval_ms=10000, is_ip6=1) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( len(self.pkt_infos) - len(dropped_packet_indexes)) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_missing_upper(self): """ missing upper layer """ p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) / UDP(sport=1234, dport=5678) / Raw()) self.extend_packet(p, 1000, self.padding) fragments = fragment_rfc8200(p, 1, 500) bad_fragment = p.__class__(scapy.compat.raw(fragments[1])) bad_fragment[IPv6ExtHdrFragment].nh = 59 bad_fragment[IPv6ExtHdrFragment].offset = 0 self.pg_enable_capture() self.src_if.add_stream([bad_fragment]) self.pg_start() pkts = self.src_if.get_capture(expected_count=1) icmp = pkts[0] self.assertIn(ICMPv6ParamProblem, icmp) self.assert_equal(icmp[ICMPv6ParamProblem].code, 3, "ICMP code") def test_invalid_frag_size(self): """ fragment size not a multiple of 8 """ p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) / UDP(sport=1234, dport=5678) / Raw()) self.extend_packet(p, 1000, self.padding) fragments = fragment_rfc8200(p, 1, 500) bad_fragment = fragments[0] self.extend_packet(bad_fragment, len(bad_fragment) + 5) self.pg_enable_capture() self.src_if.add_stream([bad_fragment]) self.pg_start() pkts = self.src_if.get_capture(expected_count=1) icmp = pkts[0] self.assertIn(ICMPv6ParamProblem, icmp) self.assert_equal(icmp[ICMPv6ParamProblem].code, 0, "ICMP code") def test_invalid_packet_size(self): """ total packet size > 65535 """ p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) / UDP(sport=1234, dport=5678) / Raw()) self.extend_packet(p, 1000, self.padding) fragments = fragment_rfc8200(p, 1, 500) bad_fragment = fragments[1] bad_fragment[IPv6ExtHdrFragment].offset = 65500 self.pg_enable_capture() self.src_if.add_stream([bad_fragment]) self.pg_start() pkts = self.src_if.get_capture(expected_count=1) icmp = pkts[0] self.assertIn(ICMPv6ParamProblem, icmp) self.assert_equal(icmp[ICMPv6ParamProblem].code, 0, "ICMP code") class TestIPv6MWReassembly(VppTestCase): """ IPv6 Reassembly (multiple workers) """ worker_config = "workers %d" % worker_count @classmethod def setUpClass(cls): super(TestIPv6MWReassembly, cls).setUpClass() cls.create_pg_interfaces(range(worker_count+1)) cls.src_if = cls.pg0 cls.send_ifs = cls.pg_interfaces[:-1] cls.dst_if = cls.pg_interfaces[-1] # setup all interfaces for i in cls.pg_interfaces: i.admin_up() i.config_ip6() i.resolve_ndp() # packets sizes reduced here because we are generating packets without # Ethernet headers, which are added later (diff fragments go via # different interfaces) cls.packet_sizes = [64-len(Ether()), 512-len(Ether()), 1518-len(Ether()), 9018-len(Ether())] cls.padding = " abcdefghijklmn" cls.create_stream(cls.packet_sizes) cls.create_fragments() @classmethod def tearDownClass(cls): super(TestIPv6MWReassembly, cls).tearDownClass() def setUp(self): """ Test setup - force timeout on existing reassemblies """ super(TestIPv6MWReassembly, self).setUp() for intf in self.send_ifs: self.vapi.ip_reassembly_enable_disable( sw_if_index=intf.sw_if_index, enable_ip6=True) self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=10, is_ip6=1) self.sleep(.25) self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=1000, is_ip6=1) def tearDown(self): super(TestIPv6MWReassembly, self).tearDown() def show_commands_at_teardown(self): self.logger.debug(self.vapi.ppcli("show ip6-full-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) @classmethod def create_stream(cls, packet_sizes, packet_count=test_packet_count): """Create input packet stream :param list packet_sizes: Required packet sizes. """ for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) p = (IPv6(src=cls.src_if.remote_ip6, }
/*
 * Copyright (c) 2019 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.
 */

#include <stdio.h>
#include <signal.h>

#include <vlibmemory/api.h>
#include <svm/fifo_segment.h>

#include <hs_apps/sapi/vpp_echo_common.h>

echo_main_t echo_main;

static void
echo_session_prealloc (echo_main_t * em)
{
  /* We need to prealloc to avoid vec resize in threads */
  echo_session_t *session;
  int i;
  for (i = 0; i < em->n_sessions; i++)
    {
      pool_get (em->sessions, session);
      clib_memset (session, 0, sizeof (*session));
      session->session_index = session - em->sessions;
      session->listener_index = SESSION_INVALID_INDEX;
      session->session_state = ECHO_SESSION_STATE_INITIAL;
    }
}

static void
echo_assert_test_suceeded (echo_main_t * em)
{
  if (em->rx_results_diff)
    CHECK_DIFF (ECHO_FAIL_TEST_ASSERT_RX_TOTAL, em->stats.rx_expected,
		em->stats.rx_total, "Invalid amount of data received");
  else
    CHECK_SAME (ECHO_FAIL_TEST_ASSERT_RX_TOTAL, em->stats.rx_expected,
		em->stats.rx_total, "Invalid amount of data received");

  if (em->tx_results_diff)
    CHECK_DIFF (ECHO_FAIL_TEST_ASSERT_TX_TOTAL, em->stats.tx_expected,
		em->stats.tx_total, "Invalid amount of data sent");
  else
    CHECK_SAME (ECHO_FAIL_TEST_ASSERT_TX_TOTAL, em->stats.tx_expected,
		em->stats.tx_total, "Invalid amount of data sent");

  clib_spinlock_lock (&em->sid_vpp_handles_lock);
  CHECK_SAME (ECHO_FAIL_TEST_ASSERT_ALL_SESSIONS_CLOSED,
	      0, hash_elts (em->session_index_by_vpp_handles),
	      "Some sessions are still open");
  clib_spinlock_unlock (&em->sid_vpp_handles_lock);
}

always_inline void
echo_session_dequeue_notify (echo_session_t * s)
{
  int rv;
  if (!svm_fifo_set_event (s->rx_fifo))
    return;
  if ((rv =
       app_send_io_evt_to_vpp (s->vpp_evt_q, s->rx_fifo->master_session_index,
			       SESSION_IO_EVT_RX, SVM_Q_WAIT)))
    ECHO_FAIL (ECHO_FAIL_SEND_IO_EVT, "app_send_io_evt_to_vpp errored %d",
	       rv);
  svm_fifo_clear_deq_ntf (s->rx_fifo);
}

static void
stop_signal (int signum)
{
  echo_main_t *em = &echo_main;
  em->time_to_stop = 1;
}

int
connect_to_vpp (char *name)
{
  echo_main_t *em = &echo_main;
  api_main_t *am = &api_main;

  if (em->use_sock_api)
    {
      if (vl_socket_client_connect ((char *) em->socket_name, name,
				    0 /* default rx, tx buffer */ ))
	{
	  ECHO_FAIL (ECHO_FAIL_SOCKET_CONNECT, "socket connect failed");
	  return -1;
	}

      if (vl_socket_client_init_shm (0, 1 /* want_pthread */ ))
	{
	  ECHO_FAIL (ECHO_FAIL_INIT_SHM_API, "init shm api failed");
	  return -1;
	}
    }
  else
    {
      if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
	{
	  ECHO_FAIL (ECHO_FAIL_SHMEM_CONNECT, "shmem connect failed");
	  return -1;
	}
    }
  em->vl_input_queue = am->shmem_hdr->vl_input_queue;
  em->my_client_index = am->my_client_index;
  return 0;
}

static void
print_global_json_stats (echo_main_t * em)
{
  u8 *start_evt =
    format (0, "%U", echo_format_timing_event, em->timing.start_event);
  u8 *end_evt =
    format (0, "%U", echo_format_timing_event, em->timing.end_event);
  u8 start_evt_missing = !(em->timing.events_sent & em->timing.start_event);
  u8 end_evt_missing = (em->rx_results_diff || em->tx_results_diff) ? 0 :
    !(em->timing.events_sent & em->timing.end_event);
  f64 deltat = start_evt_missing || end_evt_missing ? 0 :
    em->timing.end_time - em->timing.start_time;

  if (start_evt_missing)
    ECHO_FAIL (ECHO_FAIL_MISSING_START_EVENT,
	       "Expected event %v to happen, but it did not!", start_evt);

  if (end_evt_missing)
    ECHO_FAIL (ECHO_FAIL_MISSING_END_EVENT,
	       "Expected event %v to happen, but it did not!", end_evt);

  fformat (stdout, "vpp_echo JSON stats:\n{\n");
  fformat (stdout, "  \"role\": \"%s\",\n",
	   em->i_am_master ? "server" : "client");
  fformat (stdout, "  \"time\": \"%.9f\",\n", deltat);
  fformat (stdout, "  \"start_evt\": \"%v\",\n", start_evt);
  fformat (stdout, "  \"start_evt_missing\": \"%s\",\n",
	   start_evt_missing ? "True" : "False");
  fformat (stdout, "  \"end_evt\": \"%v\",\n", end_evt);
  fformat (stdout, "  \"end_evt_missing\": \"%s\",\n",
	   end_evt_missing ? "True" : "False");
  fformat (stdout, "  \"rx_data\": %lld,\n", em->stats.rx_total);
  fformat (stdout, "  \"tx_rx\": %lld,\n", em->stats.tx_total);
  fformat (stdout, "  \"closing\": {\n");
  fformat (stdout, "    \"reset\": { \"q\": %d, \"s\": %d },\n",
	   em->stats.reset_count.q, em->stats.reset_count.s);
  fformat (stdout, "    \"close\": { \"q\": %d, \"s\": %d },\n",
	   em->stats.close_count.q, em->stats.close_count.s);
  fformat (stdout, "    \"active\": { \"q\": %d, \"s\": %d },\n",
	   em->stats.active_count.q, em->stats.active_count.s);
  fformat (stdout,