blob: 1e02801cda9a5f57d7d18f45f6632c5e9a49d220 [file] [log] [blame]
Klement Sekeraf62ae122016-10-11 11:47:09 +02001import os
Dmitry Valter71d02aa2023-01-27 12:49:55 +00002import shutil
Paul Vinciguerra582eac52020-04-03 12:18:40 -04003import socket
snaramre5d4b8912019-12-13 23:39:35 +00004from socket import inet_pton, inet_ntop
Klement Sekerab91017a2017-02-09 06:04:36 +01005import struct
Paul Vinciguerra582eac52020-04-03 12:18:40 -04006import time
Klement Sekera97f6edc2017-01-12 07:17:01 +01007from traceback import format_exc, format_stack
Dave Wallace8800f732023-08-31 00:47:44 -04008from sh import tshark
9from pathlib import Path
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -070010
Klement Sekerab23ffd72021-05-31 16:08:53 +020011from config import config
Klement Sekera0e3c0de2016-09-29 14:43:44 +020012from scapy.utils import wrpcap, rdpcap, PcapReader
Klement Sekera97f6edc2017-01-12 07:17:01 +010013from scapy.plist import PacketList
Klement Sekeraf62ae122016-10-11 11:47:09 +020014from vpp_interface import VppInterface
Neale Ranns6197cb72021-06-03 14:43:21 +000015from vpp_papi import VppEnum
Klement Sekeraf62ae122016-10-11 11:47:09 +020016
Matej Klotton0178d522016-11-04 11:11:44 +010017from scapy.layers.l2 import Ether, ARP
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020018from scapy.layers.inet6 import (
19 IPv6,
20 ICMPv6ND_NS,
21 ICMPv6ND_NA,
22 ICMPv6NDOptSrcLLAddr,
23 ICMPv6NDOptDstLLAddr,
24 ICMPv6ND_RA,
25 RouterAlert,
26 IPv6ExtHdrHopByHop,
27)
Klement Sekera26cd0242022-02-18 10:35:08 +000028from util import ppp, ppc, UnexpectedPacketError
Neale Ranns75152282017-01-09 01:00:45 -080029from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
Klement Sekeraf62ae122016-10-11 11:47:09 +020030
Klement Sekerada505f62017-01-04 12:58:53 +010031
Klement Sekeraacb9b8e2017-02-14 02:55:31 +010032class CaptureTimeoutError(Exception):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020033 """Exception raised if capture or packet doesn't appear within timeout"""
34
Klement Sekeraacb9b8e2017-02-14 02:55:31 +010035 pass
36
37
Klement Sekera65cc8c02016-12-18 15:49:54 +010038def is_ipv6_misc(p):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020039 """Is packet one of uninteresting IPv6 broadcasts?"""
Klement Sekera65cc8c02016-12-18 15:49:54 +010040 if p.haslayer(ICMPv6ND_RA):
Neale Ranns75152282017-01-09 01:00:45 -080041 if in6_ismaddr(p[IPv6].dst):
42 return True
Klement Sekera65cc8c02016-12-18 15:49:54 +010043 if p.haslayer(IPv6ExtHdrHopByHop):
44 for o in p[IPv6ExtHdrHopByHop].options:
45 if isinstance(o, RouterAlert):
46 return True
47 return False
48
49
Klement Sekeraf62ae122016-10-11 11:47:09 +020050class VppPGInterface(VppInterface):
51 """
52 VPP packet-generator interface
53 """
54
55 @property
56 def pg_index(self):
57 """packet-generator interface index assigned by VPP"""
58 return self._pg_index
59
60 @property
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +020061 def gso_enabled(self):
62 """gso enabled on packet-generator interface"""
63 if self._gso_enabled == 0:
64 return "gso-disabled"
65 return "gso-enabled"
66
67 @property
68 def gso_size(self):
69 """gso size on packet-generator interface"""
70 return self._gso_size
71
72 @property
Mohsin Kazmif382b062020-08-11 15:00:44 +020073 def coalesce_is_enabled(self):
74 """coalesce enabled on packet-generator interface"""
75 if self._coalesce_enabled == 0:
76 return "coalesce-disabled"
77 return "coalesce-enabled"
78
79 @property
Klement Sekeraf62ae122016-10-11 11:47:09 +020080 def out_path(self):
81 """pcap file path - captured packets"""
82 return self._out_path
83
Klement Sekera7ba9fae2021-03-31 13:36:38 +020084 def get_in_path(self, worker):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020085 """pcap file path - injected packets"""
Klement Sekera7ba9fae2021-03-31 13:36:38 +020086 if worker is not None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020087 return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index, worker)
Klement Sekera7ba9fae2021-03-31 13:36:38 +020088 return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +020089
90 @property
91 def capture_cli(self):
92 """CLI string to start capture on this interface"""
93 return self._capture_cli
94
Klement Sekera7ba9fae2021-03-31 13:36:38 +020095 def get_cap_name(self, worker=None):
96 """return capture name for this interface and given worker"""
97 if worker is not None:
98 return self._cap_name + "-worker%d" % worker
Klement Sekeraf62ae122016-10-11 11:47:09 +020099 return self._cap_name
100
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200101 def get_input_cli(self, nb_replays=None, worker=None):
102 """return CLI string to load the injected packets"""
103 input_cli = "packet-generator new pcap %s source pg%u name %s" % (
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200104 self.get_in_path(worker),
105 self.pg_index,
106 self.get_cap_name(worker),
107 )
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200108 if nb_replays is not None:
109 return "%s limit %d" % (input_cli, nb_replays)
110 if worker is not None:
111 return "%s worker %d" % (input_cli, worker)
112 return input_cli
Klement Sekeraf62ae122016-10-11 11:47:09 +0200113
Klement Sekera778c2762016-11-08 02:00:28 +0100114 @property
115 def in_history_counter(self):
116 """Self-incrementing counter used when renaming old pcap files"""
117 v = self._in_history_counter
118 self._in_history_counter += 1
119 return v
120
121 @property
122 def out_history_counter(self):
123 """Self-incrementing counter used when renaming old pcap files"""
124 v = self._out_history_counter
125 self._out_history_counter += 1
126 return v
127
Neale Ranns6197cb72021-06-03 14:43:21 +0000128 def __init__(self, test, pg_index, gso, gso_size, mode):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200129 """Create VPP packet-generator interface"""
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200130 super().__init__(test)
Klement Sekeraa98346f2018-05-16 10:52:45 +0200131
Neale Ranns6197cb72021-06-03 14:43:21 +0000132 r = test.vapi.pg_create_interface_v2(pg_index, gso, gso_size, mode)
Klement Sekera31da2e32018-06-24 22:49:55 +0200133 self.set_sw_if_index(r.sw_if_index)
134
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100135 self._in_history_counter = 0
136 self._out_history_counter = 0
Klement Sekera97f6edc2017-01-12 07:17:01 +0100137 self._out_assert_counter = 0
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100138 self._pg_index = pg_index
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +0200139 self._gso_enabled = gso
140 self._gso_size = gso_size
Mohsin Kazmif382b062020-08-11 15:00:44 +0200141 self._coalesce_enabled = 0
Klement Sekera74dcdbf2016-11-14 09:49:09 +0100142 self._out_file = "pg%u_out.pcap" % self.pg_index
Klement Sekera778c2762016-11-08 02:00:28 +0100143 self._out_path = self.test.tempdir + "/" + self._out_file
Klement Sekeraf62ae122016-10-11 11:47:09 +0200144 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200145 self.pg_index,
146 self.out_path,
147 )
148 self._cap_name = "pcap%u-sw_if_index-%s" % (self.pg_index, self.sw_if_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200149
Dave Wallace8800f732023-08-31 00:47:44 -0400150 def link_pcap_file(self, path, direction, counter):
Klement Sekerab23ffd72021-05-31 16:08:53 +0200151 if not config.keep_pcaps:
Klement Sekerab23ffd72021-05-31 16:08:53 +0200152 return
Dave Wallace8800f732023-08-31 00:47:44 -0400153 filename = os.path.basename(path)
154 test_name = (
155 self.test_name
156 if hasattr(self, "test_name")
157 else f"suite{self.test.__name__}"
158 )
159 name = f"{self.test.tempdir}/{test_name}.[timestamp:{time.time():.8f}].{self.name}-{direction}-{counter:04}.{filename}"
160 if os.path.isfile(name):
161 self.test.logger.debug(
162 f"Skipping hard link creation: {name} already exists!"
163 )
164 return
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400165 try:
166 if os.path.isfile(path):
Dave Wallace8800f732023-08-31 00:47:44 -0400167 self.test.logger.debug(f"Creating hard link {path}->{name}")
168 os.link(path, name)
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400169 except OSError:
Dave Wallace8800f732023-08-31 00:47:44 -0400170 self.test.logger.debug(
171 f"OSError: Could not create hard link {path}->{name}"
172 )
173
174 def remove_old_pcap_file(self, path):
Dave Wallace87a88262023-11-27 20:23:03 -0500175 self.wait_for_pg_stop()
176 self.test.unlink_testcase_file(self.test, Path(path))
Dave Wallace8800f732023-08-31 00:47:44 -0400177 return
178
179 def decode_pcap_files(self, pcap_dir, filename_prefix):
180 # Generate tshark packet trace of testcase pcap files
181 pg_decode = f"{pcap_dir}/pcap-decode-{filename_prefix}.txt"
182 if os.path.isfile(pg_decode):
183 self.test.logger.debug(
184 f"The pg streams decode file already exists: {pg_decode}"
185 )
186 return
187 self.test.logger.debug(
188 f"Generating testcase pg streams decode file: {pg_decode}"
189 )
Dave Wallace0da08832024-07-16 12:36:38 -0400190 ts_opts = "-Vxr"
Dave Wallace8800f732023-08-31 00:47:44 -0400191 for p in sorted(Path(pcap_dir).glob(f"{filename_prefix}*.pcap")):
192 self.test.logger.debug(f"Decoding {p}")
193 with open(f"{pg_decode}", "a", buffering=1) as f:
194 print(f"tshark {ts_opts} {p}", file=f)
195 tshark(ts_opts, f"{p}", _out=f)
196 print("", file=f)
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400197
Klement Sekerada505f62017-01-04 12:58:53 +0100198 def enable_capture(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200199 """Enable capture on this packet-generator interface
200 of at most n packets.
201 If n < 0, this is no limit
Alexandre Poirriera618e202019-05-07 10:43:41 +0200202 """
Andrew Yourtchenkocb265c62019-07-25 10:03:51 +0000203 # disable the capture to flush the capture
204 self.disable_capture()
Dave Wallace8800f732023-08-31 00:47:44 -0400205 self.remove_old_pcap_file(self.out_path)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200206 # FIXME this should be an API, but no such exists atm
207 self.test.vapi.cli(self.capture_cli)
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200208 self._pcap_reader = None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200209
Alexandre Poirriera618e202019-05-07 10:43:41 +0200210 def disable_capture(self):
211 self.test.vapi.cli("%s disable" % self.capture_cli)
212
Mohsin Kazmif382b062020-08-11 15:00:44 +0200213 def coalesce_enable(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200214 """Enable packet coalesce on this packet-generator interface"""
Mohsin Kazmif382b062020-08-11 15:00:44 +0200215 self._coalesce_enabled = 1
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200216 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 1)
Mohsin Kazmif382b062020-08-11 15:00:44 +0200217
218 def coalesce_disable(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200219 """Disable packet coalesce on this packet-generator interface"""
Mohsin Kazmif382b062020-08-11 15:00:44 +0200220 self._coalesce_enabled = 0
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200221 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 0)
Mohsin Kazmif382b062020-08-11 15:00:44 +0200222
Klement Sekera4ecbf102019-07-31 13:14:16 +0000223 def add_stream(self, pkts, nb_replays=None, worker=None):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200224 """
225 Add a stream of packets to this packet-generator
226
227 :param pkts: iterable packets
228
229 """
Dave Wallace8800f732023-08-31 00:47:44 -0400230 in_pcap = self.get_in_path(worker)
231 if os.path.isfile(in_pcap):
232 self.remove_old_pcap_file(in_pcap)
233 wrpcap(in_pcap, pkts)
Klement Sekera3ff6ffc2021-04-01 18:19:29 +0200234 self.test.register_pcap(self, worker)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200235 # FIXME this should be an API, but no such exists atm
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200236 self.test.vapi.cli(self.get_input_cli(nb_replays, worker))
Dave Wallace8800f732023-08-31 00:47:44 -0400237 self.link_pcap_file(self.get_in_path(worker), "inp", self.in_history_counter)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200238
Klement Sekera97f6edc2017-01-12 07:17:01 +0100239 def generate_debug_aid(self, kind):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200240 """Create a hardlink to the out file with a counter and a file
Klement Sekera97f6edc2017-01-12 07:17:01 +0100241 containing stack trace to ease debugging in case of multiple capture
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200242 files present."""
243 self.test.logger.debug("Generating debug aid for %s on %s" % (kind, self._name))
244 link_path, stack_path = [
245 "%s/debug_%s_%s_%s.%s"
246 % (self.test.tempdir, self._name, self._out_assert_counter, kind, suffix)
247 for suffix in ["pcap", "stack"]
248 ]
Klement Sekera97f6edc2017-01-12 07:17:01 +0100249 os.link(self.out_path, link_path)
250 with open(stack_path, "w") as f:
251 f.writelines(format_stack())
252 self._out_assert_counter += 1
253
Klement Sekeradab231a2016-12-21 08:50:14 +0100254 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200255 """Helper method to get capture and filter it"""
Klement Sekeraf62ae122016-10-11 11:47:09 +0200256 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100257 if not self.wait_for_capture_file(timeout):
258 return None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200259 output = rdpcap(self.out_path)
Dave Wallace8800f732023-08-31 00:47:44 -0400260 self.test.logger.debug(f"Capture has {len(output.res)} packets")
Klement Sekeradab231a2016-12-21 08:50:14 +0100261 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200262 self.test.logger.debug(
263 "Exception in scapy.rdpcap (%s): %s" % (self.out_path, format_exc())
264 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100265 return None
Klement Sekera65cc8c02016-12-18 15:49:54 +0100266 before = len(output.res)
Klement Sekeradab231a2016-12-21 08:50:14 +0100267 if filter_out_fn:
268 output.res = [p for p in output.res if not filter_out_fn(p)]
Klement Sekera97f6edc2017-01-12 07:17:01 +0100269 removed = before - len(output.res)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100270 if removed:
271 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200272 "Filtered out %s packets from capture (returning %s)"
273 % (removed, len(output.res))
274 )
Klement Sekeraf62ae122016-10-11 11:47:09 +0200275 return output
Matej Klotton0178d522016-11-04 11:11:44 +0100276
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200277 def get_capture(
278 self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc
279 ):
280 """Get captured packets
Klement Sekeradab231a2016-12-21 08:50:14 +0100281
282 :param expected_count: expected number of packets to capture, if None,
283 then self.test.packet_count_for_dst_pg_idx is
284 used to lookup the expected count
285 :param remark: remark printed into debug logs
286 :param timeout: how long to wait for packets
287 :param filter_out_fn: filter applied to each packet, packets for which
288 the filter returns True are removed from capture
289 :returns: iterable packets
290 """
291 remaining_time = timeout
292 capture = None
293 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
294 based_on = "based on provided argument"
295 if expected_count is None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200296 expected_count = self.test.get_packet_count_for_if_idx(self.sw_if_index)
Klement Sekeradab231a2016-12-21 08:50:14 +0100297 based_on = "based on stored packet_infos"
Klement Sekerac86fa022017-01-02 09:03:47 +0100298 if expected_count == 0:
299 raise Exception(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200300 "Internal error, expected packet count for %s is 0!" % name
301 )
302 self.test.logger.debug(
303 "Expecting to capture %s (%s) packets on %s"
304 % (expected_count, based_on, name)
305 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100306 while remaining_time > 0:
307 before = time.time()
308 capture = self._get_capture(remaining_time, filter_out_fn)
309 elapsed_time = time.time() - before
310 if capture:
311 if len(capture.res) == expected_count:
312 # bingo, got the packets we expected
313 return capture
Jan Gelety057bb8c2016-12-20 17:32:45 +0100314 elif len(capture.res) > expected_count:
Dave Wallace8800f732023-08-31 00:47:44 -0400315 self.test.logger.error(
316 ppc(
317 f"Unexpected packets captured, got {len(capture.res)}, expected {expected_count}:",
318 capture,
319 )
320 )
Jan Gelety057bb8c2016-12-20 17:32:45 +0100321 break
Klement Sekera97f6edc2017-01-12 07:17:01 +0100322 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200323 self.test.logger.debug(
324 "Partial capture containing %s "
325 "packets doesn't match expected "
326 "count %s (yet?)" % (len(capture.res), expected_count)
327 )
Klement Sekera97f6edc2017-01-12 07:17:01 +0100328 elif expected_count == 0:
329 # bingo, got None as we expected - return empty capture
330 return PacketList()
Klement Sekeradab231a2016-12-21 08:50:14 +0100331 remaining_time -= elapsed_time
332 if capture:
Klement Sekera97f6edc2017-01-12 07:17:01 +0100333 self.generate_debug_aid("count-mismatch")
Klement Sekera26cd0242022-02-18 10:35:08 +0000334 if len(capture) > 0 and 0 == expected_count:
335 rem = f"\n{remark}" if remark else ""
336 raise UnexpectedPacketError(
Dave Wallace8800f732023-08-31 00:47:44 -0400337 capture[0],
338 f"\n({len(capture)} packets captured in total){rem} on {name}",
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200339 )
Dave Wallace8800f732023-08-31 00:47:44 -0400340 msg = f"Captured packets mismatch, captured {len(capture.res)} packets, expected {expected_count} packets on {name}:"
341 raise Exception(f"{ppc(msg, capture)}")
Klement Sekeradab231a2016-12-21 08:50:14 +0100342 else:
Klement Sekera16ce09d2022-04-23 11:34:29 +0200343 if 0 == expected_count:
344 return
Dave Wallace8800f732023-08-31 00:47:44 -0400345 raise Exception(f"No packets captured on {name} (timeout = {timeout}s)")
Klement Sekeradab231a2016-12-21 08:50:14 +0100346
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200347 def assert_nothing_captured(
348 self, timeout=1, remark=None, filter_out_fn=is_ipv6_misc
349 ):
350 """Assert that nothing unfiltered was captured on interface
Klement Sekeradab231a2016-12-21 08:50:14 +0100351
352 :param remark: remark printed into debug logs
353 :param filter_out_fn: filter applied to each packet, packets for which
354 the filter returns True are removed from capture
355 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200356 capture = self.get_capture(
357 0, timeout=timeout, remark=remark, filter_out_fn=filter_out_fn
358 )
Klement Sekera16ce09d2022-04-23 11:34:29 +0200359 if not capture or len(capture.res) == 0:
360 # junk filtered out, we're good
361 return
Klement Sekera9225dee2016-12-12 08:36:58 +0100362
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000363 def wait_for_pg_stop(self):
364 # wait till packet-generator is stopped
365 # "show packet-generator" while it is still running gives this:
366 # Name Enabled Count Parameters
367 # pcap0-sw_if_inde Yes 64 limit 64, ...
368 #
369 # also have a 5-minute timeout just in case things go terribly wrong...
370 deadline = time.time() + 300
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200371 while self.test.vapi.cli("show packet-generator").find("Yes") != -1:
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000372 self._test.sleep(0.01) # yield
373 if time.time() > deadline:
374 self.test.logger.debug("Timeout waiting for pg to stop")
375 break
376
Klement Sekera9225dee2016-12-12 08:36:58 +0100377 def wait_for_capture_file(self, timeout=1):
378 """
379 Wait until pcap capture file appears
380
381 :param timeout: How long to wait for the packet (default 1s)
382
Klement Sekeradab231a2016-12-21 08:50:14 +0100383 :returns: True/False if the file is present or appears within timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100384 """
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000385 self.wait_for_pg_stop()
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100386 deadline = time.time() + timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100387 if not os.path.isfile(self.out_path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200388 self.test.logger.debug(
Dave Wallace8800f732023-08-31 00:47:44 -0400389 f"Waiting for capture file {self.out_path} to appear, timeout is {timeout}s\n"
390 f"{' '.join(format_stack(limit=10))}"
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200391 )
Klement Sekera9225dee2016-12-12 08:36:58 +0100392 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200393 self.test.logger.debug("Capture file %s already exists" % self.out_path)
Dave Wallace8800f732023-08-31 00:47:44 -0400394 self.link_pcap_file(self.out_path, "out", self.out_history_counter)
Klement Sekeradab231a2016-12-21 08:50:14 +0100395 return True
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100396 while time.time() < deadline:
Klement Sekera9225dee2016-12-12 08:36:58 +0100397 if os.path.isfile(self.out_path):
398 break
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700399 self._test.sleep(0) # yield
Klement Sekera9225dee2016-12-12 08:36:58 +0100400 if os.path.isfile(self.out_path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200401 self.test.logger.debug(
402 "Capture file appeared after %fs" % (time.time() - (deadline - timeout))
403 )
Klement Sekera9225dee2016-12-12 08:36:58 +0100404 else:
405 self.test.logger.debug("Timeout - capture file still nowhere")
Klement Sekeradab231a2016-12-21 08:50:14 +0100406 return False
Dave Wallace8800f732023-08-31 00:47:44 -0400407 self.link_pcap_file(self.out_path, "out", self.out_history_counter)
Klement Sekeradab231a2016-12-21 08:50:14 +0100408 return True
Klement Sekera9225dee2016-12-12 08:36:58 +0100409
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100410 def verify_enough_packet_data_in_pcap(self):
Klement Sekerab91017a2017-02-09 06:04:36 +0100411 """
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100412 Check if enough data is available in file handled by internal pcap
413 reader so that a whole packet can be read.
Klement Sekerab91017a2017-02-09 06:04:36 +0100414
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100415 :returns: True if enough data present, else False
Klement Sekerab91017a2017-02-09 06:04:36 +0100416 """
417 orig_pos = self._pcap_reader.f.tell() # save file position
418 enough_data = False
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100419 # read packet header from pcap
420 packet_header_size = 16
421 caplen = None
422 end_pos = None
423 hdr = self._pcap_reader.f.read(packet_header_size)
424 if len(hdr) == packet_header_size:
425 # parse the capture length - caplen
Klement Sekerab91017a2017-02-09 06:04:36 +0100426 sec, usec, caplen, wirelen = struct.unpack(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200427 self._pcap_reader.endian + "IIII", hdr
428 )
Klement Sekerab91017a2017-02-09 06:04:36 +0100429 self._pcap_reader.f.seek(0, 2) # seek to end of file
430 end_pos = self._pcap_reader.f.tell() # get position at end
431 if end_pos >= orig_pos + len(hdr) + caplen:
432 enough_data = True # yay, we have enough data
Klement Sekerab91017a2017-02-09 06:04:36 +0100433 self._pcap_reader.f.seek(orig_pos, 0) # restore original position
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100434 return enough_data
Klement Sekerab91017a2017-02-09 06:04:36 +0100435
Klement Sekeradab231a2016-12-21 08:50:14 +0100436 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200437 """
438 Wait for next packet captured with a timeout
439
440 :param timeout: How long to wait for the packet
441
442 :returns: Captured packet if no packet arrived within timeout
443 :raises Exception: if no packet arrives within timeout
444 """
Klement Sekeradab231a2016-12-21 08:50:14 +0100445 deadline = time.time() + timeout
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200446 if self._pcap_reader is None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100447 if not self.wait_for_capture_file(timeout):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200448 raise CaptureTimeoutError(
449 "Capture file %s did not appear within timeout" % self.out_path
450 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100451 while time.time() < deadline:
452 try:
453 self._pcap_reader = PcapReader(self.out_path)
454 break
455 except:
Klement Sekerada505f62017-01-04 12:58:53 +0100456 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200457 "Exception in scapy.PcapReader(%s): %s"
458 % (self.out_path, format_exc())
459 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100460 if not self._pcap_reader:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200461 raise CaptureTimeoutError(
462 "Capture file %s did not appear within timeout" % self.out_path
463 )
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200464
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100465 poll = False
466 if timeout > 0:
467 self.test.logger.debug("Waiting for packet")
468 else:
469 poll = True
470 self.test.logger.debug("Polling for packet")
471 while time.time() < deadline or poll:
472 if not self.verify_enough_packet_data_in_pcap():
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700473 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100474 poll = False
475 continue
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200476 p = self._pcap_reader.recv()
477 if p is not None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100478 if filter_out_fn is not None and filter_out_fn(p):
479 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200480 "Packet received after %ss was filtered out"
481 % (time.time() - (deadline - timeout))
482 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100483 else:
Klement Sekerada505f62017-01-04 12:58:53 +0100484 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200485 "Packet received after %fs"
486 % (time.time() - (deadline - timeout))
487 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100488 return p
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700489 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100490 poll = False
Dave Wallace8800f732023-08-31 00:47:44 -0400491 self.test.logger.debug(f"Timeout ({timeout}) - no packets received")
492 raise CaptureTimeoutError(f"Packet didn't arrive within timeout ({timeout})")
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200493
Matej Klotton0178d522016-11-04 11:11:44 +0100494 def create_arp_req(self):
495 """Create ARP request applicable for this interface"""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200496 return Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) / ARP(
497 op=ARP.who_has,
498 pdst=self.local_ip4,
499 psrc=self.remote_ip4,
500 hwsrc=self.remote_mac,
501 )
Matej Klotton0178d522016-11-04 11:11:44 +0100502
Benoît Ganne2699fe22021-01-18 19:25:38 +0100503 def create_ndp_req(self, addr=None):
Matej Klotton0178d522016-11-04 11:11:44 +0100504 """Create NDP - NS applicable for this interface"""
Benoît Ganne2699fe22021-01-18 19:25:38 +0100505 if not addr:
506 addr = self.local_ip6
507 nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr))
Neale Ranns465a1a32017-01-07 10:04:09 -0800508 d = inet_ntop(socket.AF_INET6, nsma)
509
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200510 return (
511 Ether(dst=in6_getnsmac(nsma))
512 / IPv6(dst=d, src=self.remote_ip6)
513 / ICMPv6ND_NS(tgt=addr)
514 / ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac)
515 )
Matej Klotton0178d522016-11-04 11:11:44 +0100516
517 def resolve_arp(self, pg_interface=None):
518 """Resolve ARP using provided packet-generator interface
519
520 :param pg_interface: interface used to resolve, if None then this
521 interface is used
522
523 """
524 if pg_interface is None:
525 pg_interface = self
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200526 self.test.logger.info(
527 "Sending ARP request for %s on port %s"
528 % (self.local_ip4, pg_interface.name)
529 )
Matej Klotton0178d522016-11-04 11:11:44 +0100530 arp_req = self.create_arp_req()
531 pg_interface.add_stream(arp_req)
532 pg_interface.enable_capture()
533 self.test.pg_start()
Klement Sekera7bb873a2016-11-18 07:38:42 +0100534 self.test.logger.info(self.test.vapi.cli("show trace"))
Klement Sekera9225dee2016-12-12 08:36:58 +0100535 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100536 captured_packet = pg_interface.wait_for_packet(1)
Klement Sekera9225dee2016-12-12 08:36:58 +0100537 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200538 self.test.logger.info("No ARP received on port %s" % pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100539 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100540 arp_reply = captured_packet.copy() # keep original for exception
Matej Klotton0178d522016-11-04 11:11:44 +0100541 try:
542 if arp_reply[ARP].op == ARP.is_at:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200543 self.test.logger.info(
544 "VPP %s MAC address is %s " % (self.name, arp_reply[ARP].hwsrc)
545 )
Matej Klotton0178d522016-11-04 11:11:44 +0100546 self._local_mac = arp_reply[ARP].hwsrc
547 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200548 self.test.logger.info("No ARP received on port %s" % pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100549 except:
Klement Sekera7bb873a2016-11-18 07:38:42 +0100550 self.test.logger.error(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200551 ppp("Unexpected response to ARP request:", captured_packet)
552 )
Matej Klotton0178d522016-11-04 11:11:44 +0100553 raise
554
Benoît Ganne2699fe22021-01-18 19:25:38 +0100555 def resolve_ndp(self, pg_interface=None, timeout=1, link_layer=False):
Matej Klotton0178d522016-11-04 11:11:44 +0100556 """Resolve NDP using provided packet-generator interface
557
558 :param pg_interface: interface used to resolve, if None then this
559 interface is used
Klement Sekeradab231a2016-12-21 08:50:14 +0100560 :param timeout: how long to wait for response before giving up
Benoît Ganne2699fe22021-01-18 19:25:38 +0100561 :param link_layer: resolve for global address if False (default)
562 or for link-layer address if True
Matej Klotton0178d522016-11-04 11:11:44 +0100563
564 """
565 if pg_interface is None:
566 pg_interface = self
Benoît Ganne2699fe22021-01-18 19:25:38 +0100567 addr = self.local_ip6_ll if link_layer else self.local_ip6
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200568 self.test.logger.info(
569 "Sending NDP request for %s on port %s" % (addr, pg_interface.name)
570 )
Benoît Ganne2699fe22021-01-18 19:25:38 +0100571 ndp_req = self.create_ndp_req(addr)
Matej Klotton0178d522016-11-04 11:11:44 +0100572 pg_interface.add_stream(ndp_req)
573 pg_interface.enable_capture()
574 self.test.pg_start()
Klement Sekeradab231a2016-12-21 08:50:14 +0100575 now = time.time()
576 deadline = now + timeout
Neale Ranns82a06a92016-12-08 20:05:33 +0000577 # Enabling IPv6 on an interface can generate more than the
578 # ND reply we are looking for (namely MLD). So loop through
579 # the replies to look for want we want.
Klement Sekeradab231a2016-12-21 08:50:14 +0100580 while now < deadline:
581 try:
582 captured_packet = pg_interface.wait_for_packet(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200583 deadline - now, filter_out_fn=None
584 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100585 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200586 self.test.logger.error("Timeout while waiting for NDP response")
Klement Sekeradab231a2016-12-21 08:50:14 +0100587 raise
588 ndp_reply = captured_packet.copy() # keep original for exception
Neale Ranns82a06a92016-12-08 20:05:33 +0000589 try:
590 ndp_na = ndp_reply[ICMPv6ND_NA]
591 opt = ndp_na[ICMPv6NDOptDstLLAddr]
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200592 self.test.logger.info(
593 "VPP %s MAC address is %s " % (self.name, opt.lladdr)
594 )
Neale Ranns82a06a92016-12-08 20:05:33 +0000595 self._local_mac = opt.lladdr
Klement Sekeradab231a2016-12-21 08:50:14 +0100596 self.test.logger.debug(self.test.vapi.cli("show trace"))
597 # we now have the MAC we've been after
598 return
Neale Ranns82a06a92016-12-08 20:05:33 +0000599 except:
600 self.test.logger.info(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200601 ppp("Unexpected response to NDP request:", captured_packet)
602 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100603 now = time.time()
604
605 self.test.logger.debug(self.test.vapi.cli("show trace"))
606 raise Exception("Timeout while waiting for NDP response")