blob: 779eb0be6d9ded7b163b5b536f15ba18d6af2695 [file] [log] [blame]
Klement Sekeraf62ae122016-10-11 11:47:09 +02001import os
Paul Vinciguerra582eac52020-04-03 12:18:40 -04002import socket
snaramre5d4b8912019-12-13 23:39:35 +00003from socket import inet_pton, inet_ntop
Klement Sekerab91017a2017-02-09 06:04:36 +01004import struct
Paul Vinciguerra582eac52020-04-03 12:18:40 -04005import time
Klement Sekera97f6edc2017-01-12 07:17:01 +01006from traceback import format_exc, format_stack
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -07007
Klement Sekerab23ffd72021-05-31 16:08:53 +02008from config import config
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -07009import scapy.compat
Klement Sekera0e3c0de2016-09-29 14:43:44 +020010from scapy.utils import wrpcap, rdpcap, PcapReader
Klement Sekera97f6edc2017-01-12 07:17:01 +010011from scapy.plist import PacketList
Klement Sekeraf62ae122016-10-11 11:47:09 +020012from vpp_interface import VppInterface
Neale Ranns6197cb72021-06-03 14:43:21 +000013from vpp_papi import VppEnum
Klement Sekeraf62ae122016-10-11 11:47:09 +020014
Matej Klotton0178d522016-11-04 11:11:44 +010015from scapy.layers.l2 import Ether, ARP
Klement Sekera0e3c0de2016-09-29 14:43:44 +020016from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
Klement Sekera65cc8c02016-12-18 15:49:54 +010017 ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
18 IPv6ExtHdrHopByHop
Klement Sekera26cd0242022-02-18 10:35:08 +000019from util import ppp, ppc, UnexpectedPacketError
Neale Ranns75152282017-01-09 01:00:45 -080020from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
Klement Sekeraf62ae122016-10-11 11:47:09 +020021
Klement Sekerada505f62017-01-04 12:58:53 +010022
Klement Sekeraacb9b8e2017-02-14 02:55:31 +010023class CaptureTimeoutError(Exception):
24 """ Exception raised if capture or packet doesn't appear within timeout """
25 pass
26
27
Klement Sekera65cc8c02016-12-18 15:49:54 +010028def is_ipv6_misc(p):
29 """ Is packet one of uninteresting IPv6 broadcasts? """
30 if p.haslayer(ICMPv6ND_RA):
Neale Ranns75152282017-01-09 01:00:45 -080031 if in6_ismaddr(p[IPv6].dst):
32 return True
Klement Sekera65cc8c02016-12-18 15:49:54 +010033 if p.haslayer(IPv6ExtHdrHopByHop):
34 for o in p[IPv6ExtHdrHopByHop].options:
35 if isinstance(o, RouterAlert):
36 return True
37 return False
38
39
Klement Sekeraf62ae122016-10-11 11:47:09 +020040class VppPGInterface(VppInterface):
41 """
42 VPP packet-generator interface
43 """
44
45 @property
46 def pg_index(self):
47 """packet-generator interface index assigned by VPP"""
48 return self._pg_index
49
50 @property
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +020051 def gso_enabled(self):
52 """gso enabled on packet-generator interface"""
53 if self._gso_enabled == 0:
54 return "gso-disabled"
55 return "gso-enabled"
56
57 @property
58 def gso_size(self):
59 """gso size on packet-generator interface"""
60 return self._gso_size
61
62 @property
Mohsin Kazmif382b062020-08-11 15:00:44 +020063 def coalesce_is_enabled(self):
64 """coalesce enabled on packet-generator interface"""
65 if self._coalesce_enabled == 0:
66 return "coalesce-disabled"
67 return "coalesce-enabled"
68
69 @property
Klement Sekeraf62ae122016-10-11 11:47:09 +020070 def out_path(self):
71 """pcap file path - captured packets"""
72 return self._out_path
73
Klement Sekera7ba9fae2021-03-31 13:36:38 +020074 def get_in_path(self, worker):
Klement Sekeraf62ae122016-10-11 11:47:09 +020075 """ pcap file path - injected packets"""
Klement Sekera7ba9fae2021-03-31 13:36:38 +020076 if worker is not None:
77 return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index,
78 worker)
79 return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +020080
81 @property
82 def capture_cli(self):
83 """CLI string to start capture on this interface"""
84 return self._capture_cli
85
Klement Sekera7ba9fae2021-03-31 13:36:38 +020086 def get_cap_name(self, worker=None):
87 """return capture name for this interface and given worker"""
88 if worker is not None:
89 return self._cap_name + "-worker%d" % worker
Klement Sekeraf62ae122016-10-11 11:47:09 +020090 return self._cap_name
91
Klement Sekera7ba9fae2021-03-31 13:36:38 +020092 def get_input_cli(self, nb_replays=None, worker=None):
93 """return CLI string to load the injected packets"""
94 input_cli = "packet-generator new pcap %s source pg%u name %s" % (
95 self.get_in_path(worker), self.pg_index, self.get_cap_name(worker))
96 if nb_replays is not None:
97 return "%s limit %d" % (input_cli, nb_replays)
98 if worker is not None:
99 return "%s worker %d" % (input_cli, worker)
100 return input_cli
Klement Sekeraf62ae122016-10-11 11:47:09 +0200101
Klement Sekera778c2762016-11-08 02:00:28 +0100102 @property
103 def in_history_counter(self):
104 """Self-incrementing counter used when renaming old pcap files"""
105 v = self._in_history_counter
106 self._in_history_counter += 1
107 return v
108
109 @property
110 def out_history_counter(self):
111 """Self-incrementing counter used when renaming old pcap files"""
112 v = self._out_history_counter
113 self._out_history_counter += 1
114 return v
115
Neale Ranns6197cb72021-06-03 14:43:21 +0000116 def __init__(self, test, pg_index, gso, gso_size, mode):
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100117 """ Create VPP packet-generator interface """
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200118 super().__init__(test)
Klement Sekeraa98346f2018-05-16 10:52:45 +0200119
Neale Ranns6197cb72021-06-03 14:43:21 +0000120 r = test.vapi.pg_create_interface_v2(pg_index, gso, gso_size, mode)
Klement Sekera31da2e32018-06-24 22:49:55 +0200121 self.set_sw_if_index(r.sw_if_index)
122
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100123 self._in_history_counter = 0
124 self._out_history_counter = 0
Klement Sekera97f6edc2017-01-12 07:17:01 +0100125 self._out_assert_counter = 0
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100126 self._pg_index = pg_index
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +0200127 self._gso_enabled = gso
128 self._gso_size = gso_size
Mohsin Kazmif382b062020-08-11 15:00:44 +0200129 self._coalesce_enabled = 0
Klement Sekera74dcdbf2016-11-14 09:49:09 +0100130 self._out_file = "pg%u_out.pcap" % self.pg_index
Klement Sekera778c2762016-11-08 02:00:28 +0100131 self._out_path = self.test.tempdir + "/" + self._out_file
Klement Sekeraf62ae122016-10-11 11:47:09 +0200132 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
133 self.pg_index, self.out_path)
Paul Vinciguerra44b0b072019-06-25 20:51:31 -0400134 self._cap_name = "pcap%u-sw_if_index-%s" % (
135 self.pg_index, self.sw_if_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200136
Klement Sekerab23ffd72021-05-31 16:08:53 +0200137 def handle_old_pcap_file(self, path, counter):
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200138 filename = os.path.basename(path)
Klement Sekerab23ffd72021-05-31 16:08:53 +0200139
140 if not config.keep_pcaps:
141 try:
142 self.test.logger.debug(f"Removing {path}")
143 os.remove(path)
144 except OSError:
145 self.test.logger.debug(f"OSError: Could not remove {path}")
146 return
147
148 # keep
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400149 try:
Klement Sekerab23ffd72021-05-31 16:08:53 +0200150
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400151 if os.path.isfile(path):
152 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
153 (self.test.tempdir,
154 time.time(),
155 self.name,
156 counter,
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200157 filename)
Klement Sekerab23ffd72021-05-31 16:08:53 +0200158 self.test.logger.debug("Renaming %s->%s" % (path, name))
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400159 os.rename(path, name)
160 except OSError:
161 self.test.logger.debug("OSError: Could not rename %s %s" %
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200162 (path, filename))
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400163
Klement Sekerada505f62017-01-04 12:58:53 +0100164 def enable_capture(self):
Alexandre Poirriera618e202019-05-07 10:43:41 +0200165 """ Enable capture on this packet-generator interface
166 of at most n packets.
167 If n < 0, this is no limit
168 """
Andrew Yourtchenkocb265c62019-07-25 10:03:51 +0000169 # disable the capture to flush the capture
170 self.disable_capture()
Klement Sekerab23ffd72021-05-31 16:08:53 +0200171 self.handle_old_pcap_file(self.out_path, self.out_history_counter)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200172 # FIXME this should be an API, but no such exists atm
173 self.test.vapi.cli(self.capture_cli)
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200174 self._pcap_reader = None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200175
Alexandre Poirriera618e202019-05-07 10:43:41 +0200176 def disable_capture(self):
177 self.test.vapi.cli("%s disable" % self.capture_cli)
178
Mohsin Kazmif382b062020-08-11 15:00:44 +0200179 def coalesce_enable(self):
180 """ Enable packet coalesce on this packet-generator interface"""
181 self._coalesce_enabled = 1
182 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index,
183 1)
184
185 def coalesce_disable(self):
186 """ Disable packet coalesce on this packet-generator interface"""
187 self._coalesce_enabled = 0
188 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index,
189 0)
190
Klement Sekera4ecbf102019-07-31 13:14:16 +0000191 def add_stream(self, pkts, nb_replays=None, worker=None):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200192 """
193 Add a stream of packets to this packet-generator
194
195 :param pkts: iterable packets
196
197 """
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200198 wrpcap(self.get_in_path(worker), pkts)
Klement Sekera3ff6ffc2021-04-01 18:19:29 +0200199 self.test.register_pcap(self, worker)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200200 # FIXME this should be an API, but no such exists atm
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200201 self.test.vapi.cli(self.get_input_cli(nb_replays, worker))
Klement Sekeraf62ae122016-10-11 11:47:09 +0200202
Klement Sekera97f6edc2017-01-12 07:17:01 +0100203 def generate_debug_aid(self, kind):
204 """ Create a hardlink to the out file with a counter and a file
205 containing stack trace to ease debugging in case of multiple capture
206 files present. """
207 self.test.logger.debug("Generating debug aid for %s on %s" %
208 (kind, self._name))
209 link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
210 (self.test.tempdir, self._name,
211 self._out_assert_counter, kind, suffix)
212 for suffix in ["pcap", "stack"]
213 ]
214 os.link(self.out_path, link_path)
215 with open(stack_path, "w") as f:
216 f.writelines(format_stack())
217 self._out_assert_counter += 1
218
Klement Sekeradab231a2016-12-21 08:50:14 +0100219 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
220 """ Helper method to get capture and filter it """
Klement Sekeraf62ae122016-10-11 11:47:09 +0200221 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100222 if not self.wait_for_capture_file(timeout):
223 return None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200224 output = rdpcap(self.out_path)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100225 self.test.logger.debug("Capture has %s packets" % len(output.res))
Klement Sekeradab231a2016-12-21 08:50:14 +0100226 except:
Jane546d3b2016-12-08 13:10:03 +0100227 self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
Klement Sekeradab231a2016-12-21 08:50:14 +0100228 (self.out_path, format_exc()))
229 return None
Klement Sekera65cc8c02016-12-18 15:49:54 +0100230 before = len(output.res)
Klement Sekeradab231a2016-12-21 08:50:14 +0100231 if filter_out_fn:
232 output.res = [p for p in output.res if not filter_out_fn(p)]
Klement Sekera97f6edc2017-01-12 07:17:01 +0100233 removed = before - len(output.res)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100234 if removed:
235 self.test.logger.debug(
236 "Filtered out %s packets from capture (returning %s)" %
237 (removed, len(output.res)))
Klement Sekeraf62ae122016-10-11 11:47:09 +0200238 return output
Matej Klotton0178d522016-11-04 11:11:44 +0100239
Klement Sekeradab231a2016-12-21 08:50:14 +0100240 def get_capture(self, expected_count=None, remark=None, timeout=1,
241 filter_out_fn=is_ipv6_misc):
242 """ Get captured packets
243
244 :param expected_count: expected number of packets to capture, if None,
245 then self.test.packet_count_for_dst_pg_idx is
246 used to lookup the expected count
247 :param remark: remark printed into debug logs
248 :param timeout: how long to wait for packets
249 :param filter_out_fn: filter applied to each packet, packets for which
250 the filter returns True are removed from capture
251 :returns: iterable packets
252 """
253 remaining_time = timeout
254 capture = None
255 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
256 based_on = "based on provided argument"
257 if expected_count is None:
258 expected_count = \
259 self.test.get_packet_count_for_if_idx(self.sw_if_index)
260 based_on = "based on stored packet_infos"
Klement Sekerac86fa022017-01-02 09:03:47 +0100261 if expected_count == 0:
262 raise Exception(
Klement Sekerada505f62017-01-04 12:58:53 +0100263 "Internal error, expected packet count for %s is 0!" %
264 name)
Jane546d3b2016-12-08 13:10:03 +0100265 self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
Klement Sekeradab231a2016-12-21 08:50:14 +0100266 expected_count, based_on, name))
Klement Sekeradab231a2016-12-21 08:50:14 +0100267 while remaining_time > 0:
268 before = time.time()
269 capture = self._get_capture(remaining_time, filter_out_fn)
270 elapsed_time = time.time() - before
271 if capture:
272 if len(capture.res) == expected_count:
273 # bingo, got the packets we expected
274 return capture
Jan Gelety057bb8c2016-12-20 17:32:45 +0100275 elif len(capture.res) > expected_count:
276 self.test.logger.error(
277 ppc("Unexpected packets captured:", capture))
278 break
Klement Sekera97f6edc2017-01-12 07:17:01 +0100279 else:
280 self.test.logger.debug("Partial capture containing %s "
281 "packets doesn't match expected "
282 "count %s (yet?)" %
283 (len(capture.res), expected_count))
284 elif expected_count == 0:
285 # bingo, got None as we expected - return empty capture
286 return PacketList()
Klement Sekeradab231a2016-12-21 08:50:14 +0100287 remaining_time -= elapsed_time
288 if capture:
Klement Sekera97f6edc2017-01-12 07:17:01 +0100289 self.generate_debug_aid("count-mismatch")
Klement Sekera26cd0242022-02-18 10:35:08 +0000290 if len(capture) > 0 and 0 == expected_count:
291 rem = f"\n{remark}" if remark else ""
292 raise UnexpectedPacketError(
293 capture[0],
294 f"\n({len(capture)} packets captured in total){rem}")
Klement Sekeradab231a2016-12-21 08:50:14 +0100295 raise Exception("Captured packets mismatch, captured %s packets, "
296 "expected %s packets on %s" %
297 (len(capture.res), expected_count, name))
298 else:
Klement Sekera16ce09d2022-04-23 11:34:29 +0200299 if 0 == expected_count:
300 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100301 raise Exception("No packets captured on %s" % name)
302
Klement Sekera26cd0242022-02-18 10:35:08 +0000303 def assert_nothing_captured(self, timeout=1, remark=None,
304 filter_out_fn=is_ipv6_misc):
Klement Sekeradab231a2016-12-21 08:50:14 +0100305 """ Assert that nothing unfiltered was captured on interface
306
307 :param remark: remark printed into debug logs
308 :param filter_out_fn: filter applied to each packet, packets for which
309 the filter returns True are removed from capture
310 """
Klement Sekera16ce09d2022-04-23 11:34:29 +0200311 capture = self.get_capture(0, timeout=timeout, remark=remark,
312 filter_out_fn=filter_out_fn)
313 if not capture or len(capture.res) == 0:
314 # junk filtered out, we're good
315 return
Klement Sekera9225dee2016-12-12 08:36:58 +0100316
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000317 def wait_for_pg_stop(self):
318 # wait till packet-generator is stopped
319 # "show packet-generator" while it is still running gives this:
320 # Name Enabled Count Parameters
321 # pcap0-sw_if_inde Yes 64 limit 64, ...
322 #
323 # also have a 5-minute timeout just in case things go terribly wrong...
324 deadline = time.time() + 300
325 while self.test.vapi.cli('show packet-generator').find("Yes") != -1:
326 self._test.sleep(0.01) # yield
327 if time.time() > deadline:
328 self.test.logger.debug("Timeout waiting for pg to stop")
329 break
330
Klement Sekera9225dee2016-12-12 08:36:58 +0100331 def wait_for_capture_file(self, timeout=1):
332 """
333 Wait until pcap capture file appears
334
335 :param timeout: How long to wait for the packet (default 1s)
336
Klement Sekeradab231a2016-12-21 08:50:14 +0100337 :returns: True/False if the file is present or appears within timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100338 """
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000339 self.wait_for_pg_stop()
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100340 deadline = time.time() + timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100341 if not os.path.isfile(self.out_path):
Klement Sekeradab231a2016-12-21 08:50:14 +0100342 self.test.logger.debug("Waiting for capture file %s to appear, "
343 "timeout is %ss" % (self.out_path, timeout))
Klement Sekera9225dee2016-12-12 08:36:58 +0100344 else:
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100345 self.test.logger.debug("Capture file %s already exists" %
346 self.out_path)
Klement Sekeradab231a2016-12-21 08:50:14 +0100347 return True
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100348 while time.time() < deadline:
Klement Sekera9225dee2016-12-12 08:36:58 +0100349 if os.path.isfile(self.out_path):
350 break
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700351 self._test.sleep(0) # yield
Klement Sekera9225dee2016-12-12 08:36:58 +0100352 if os.path.isfile(self.out_path):
353 self.test.logger.debug("Capture file appeared after %fs" %
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100354 (time.time() - (deadline - timeout)))
Klement Sekera9225dee2016-12-12 08:36:58 +0100355 else:
356 self.test.logger.debug("Timeout - capture file still nowhere")
Klement Sekeradab231a2016-12-21 08:50:14 +0100357 return False
358 return True
Klement Sekera9225dee2016-12-12 08:36:58 +0100359
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100360 def verify_enough_packet_data_in_pcap(self):
Klement Sekerab91017a2017-02-09 06:04:36 +0100361 """
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100362 Check if enough data is available in file handled by internal pcap
363 reader so that a whole packet can be read.
Klement Sekerab91017a2017-02-09 06:04:36 +0100364
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100365 :returns: True if enough data present, else False
Klement Sekerab91017a2017-02-09 06:04:36 +0100366 """
367 orig_pos = self._pcap_reader.f.tell() # save file position
368 enough_data = False
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100369 # read packet header from pcap
370 packet_header_size = 16
371 caplen = None
372 end_pos = None
373 hdr = self._pcap_reader.f.read(packet_header_size)
374 if len(hdr) == packet_header_size:
375 # parse the capture length - caplen
Klement Sekerab91017a2017-02-09 06:04:36 +0100376 sec, usec, caplen, wirelen = struct.unpack(
377 self._pcap_reader.endian + "IIII", hdr)
378 self._pcap_reader.f.seek(0, 2) # seek to end of file
379 end_pos = self._pcap_reader.f.tell() # get position at end
380 if end_pos >= orig_pos + len(hdr) + caplen:
381 enough_data = True # yay, we have enough data
Klement Sekerab91017a2017-02-09 06:04:36 +0100382 self._pcap_reader.f.seek(orig_pos, 0) # restore original position
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100383 return enough_data
Klement Sekerab91017a2017-02-09 06:04:36 +0100384
Klement Sekeradab231a2016-12-21 08:50:14 +0100385 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200386 """
387 Wait for next packet captured with a timeout
388
389 :param timeout: How long to wait for the packet
390
391 :returns: Captured packet if no packet arrived within timeout
392 :raises Exception: if no packet arrives within timeout
393 """
Klement Sekeradab231a2016-12-21 08:50:14 +0100394 deadline = time.time() + timeout
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200395 if self._pcap_reader is None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100396 if not self.wait_for_capture_file(timeout):
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100397 raise CaptureTimeoutError("Capture file %s did not appear "
398 "within timeout" % self.out_path)
Klement Sekeradab231a2016-12-21 08:50:14 +0100399 while time.time() < deadline:
400 try:
401 self._pcap_reader = PcapReader(self.out_path)
402 break
403 except:
Klement Sekerada505f62017-01-04 12:58:53 +0100404 self.test.logger.debug(
Klement Sekera97f6edc2017-01-12 07:17:01 +0100405 "Exception in scapy.PcapReader(%s): %s" %
Klement Sekerada505f62017-01-04 12:58:53 +0100406 (self.out_path, format_exc()))
Klement Sekeradab231a2016-12-21 08:50:14 +0100407 if not self._pcap_reader:
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100408 raise CaptureTimeoutError("Capture file %s did not appear within "
409 "timeout" % self.out_path)
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200410
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100411 poll = False
412 if timeout > 0:
413 self.test.logger.debug("Waiting for packet")
414 else:
415 poll = True
416 self.test.logger.debug("Polling for packet")
417 while time.time() < deadline or poll:
418 if not self.verify_enough_packet_data_in_pcap():
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700419 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100420 poll = False
421 continue
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200422 p = self._pcap_reader.recv()
423 if p is not None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100424 if filter_out_fn is not None and filter_out_fn(p):
425 self.test.logger.debug(
426 "Packet received after %ss was filtered out" %
427 (time.time() - (deadline - timeout)))
428 else:
Klement Sekerada505f62017-01-04 12:58:53 +0100429 self.test.logger.debug(
430 "Packet received after %fs" %
431 (time.time() - (deadline - timeout)))
Klement Sekeradab231a2016-12-21 08:50:14 +0100432 return p
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700433 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100434 poll = False
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200435 self.test.logger.debug("Timeout - no packets received")
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100436 raise CaptureTimeoutError("Packet didn't arrive within timeout")
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200437
Matej Klotton0178d522016-11-04 11:11:44 +0100438 def create_arp_req(self):
439 """Create ARP request applicable for this interface"""
440 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
441 ARP(op=ARP.who_has, pdst=self.local_ip4,
442 psrc=self.remote_ip4, hwsrc=self.remote_mac))
443
Benoît Ganne2699fe22021-01-18 19:25:38 +0100444 def create_ndp_req(self, addr=None):
Matej Klotton0178d522016-11-04 11:11:44 +0100445 """Create NDP - NS applicable for this interface"""
Benoît Ganne2699fe22021-01-18 19:25:38 +0100446 if not addr:
447 addr = self.local_ip6
448 nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr))
Neale Ranns465a1a32017-01-07 10:04:09 -0800449 d = inet_ntop(socket.AF_INET6, nsma)
450
451 return (Ether(dst=in6_getnsmac(nsma)) /
452 IPv6(dst=d, src=self.remote_ip6) /
Benoît Ganne2699fe22021-01-18 19:25:38 +0100453 ICMPv6ND_NS(tgt=addr) /
Klement Sekera74dcdbf2016-11-14 09:49:09 +0100454 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
Matej Klotton0178d522016-11-04 11:11:44 +0100455
456 def resolve_arp(self, pg_interface=None):
457 """Resolve ARP using provided packet-generator interface
458
459 :param pg_interface: interface used to resolve, if None then this
460 interface is used
461
462 """
463 if pg_interface is None:
464 pg_interface = self
Klement Sekera7bb873a2016-11-18 07:38:42 +0100465 self.test.logger.info("Sending ARP request for %s on port %s" %
466 (self.local_ip4, pg_interface.name))
Matej Klotton0178d522016-11-04 11:11:44 +0100467 arp_req = self.create_arp_req()
468 pg_interface.add_stream(arp_req)
469 pg_interface.enable_capture()
470 self.test.pg_start()
Klement Sekera7bb873a2016-11-18 07:38:42 +0100471 self.test.logger.info(self.test.vapi.cli("show trace"))
Klement Sekera9225dee2016-12-12 08:36:58 +0100472 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100473 captured_packet = pg_interface.wait_for_packet(1)
Klement Sekera9225dee2016-12-12 08:36:58 +0100474 except:
475 self.test.logger.info("No ARP received on port %s" %
476 pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100477 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100478 arp_reply = captured_packet.copy() # keep original for exception
Matej Klotton0178d522016-11-04 11:11:44 +0100479 try:
480 if arp_reply[ARP].op == ARP.is_at:
Klement Sekera7bb873a2016-11-18 07:38:42 +0100481 self.test.logger.info("VPP %s MAC address is %s " %
482 (self.name, arp_reply[ARP].hwsrc))
Matej Klotton0178d522016-11-04 11:11:44 +0100483 self._local_mac = arp_reply[ARP].hwsrc
484 else:
Klement Sekeradab231a2016-12-21 08:50:14 +0100485 self.test.logger.info("No ARP received on port %s" %
486 pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100487 except:
Klement Sekera7bb873a2016-11-18 07:38:42 +0100488 self.test.logger.error(
Klement Sekeradab231a2016-12-21 08:50:14 +0100489 ppp("Unexpected response to ARP request:", captured_packet))
Matej Klotton0178d522016-11-04 11:11:44 +0100490 raise
491
Benoît Ganne2699fe22021-01-18 19:25:38 +0100492 def resolve_ndp(self, pg_interface=None, timeout=1, link_layer=False):
Matej Klotton0178d522016-11-04 11:11:44 +0100493 """Resolve NDP using provided packet-generator interface
494
495 :param pg_interface: interface used to resolve, if None then this
496 interface is used
Klement Sekeradab231a2016-12-21 08:50:14 +0100497 :param timeout: how long to wait for response before giving up
Benoît Ganne2699fe22021-01-18 19:25:38 +0100498 :param link_layer: resolve for global address if False (default)
499 or for link-layer address if True
Matej Klotton0178d522016-11-04 11:11:44 +0100500
501 """
502 if pg_interface is None:
503 pg_interface = self
Benoît Ganne2699fe22021-01-18 19:25:38 +0100504 addr = self.local_ip6_ll if link_layer else self.local_ip6
Klement Sekera7bb873a2016-11-18 07:38:42 +0100505 self.test.logger.info("Sending NDP request for %s on port %s" %
Benoît Ganne2699fe22021-01-18 19:25:38 +0100506 (addr, pg_interface.name))
507 ndp_req = self.create_ndp_req(addr)
Matej Klotton0178d522016-11-04 11:11:44 +0100508 pg_interface.add_stream(ndp_req)
509 pg_interface.enable_capture()
510 self.test.pg_start()
Klement Sekeradab231a2016-12-21 08:50:14 +0100511 now = time.time()
512 deadline = now + timeout
Neale Ranns82a06a92016-12-08 20:05:33 +0000513 # Enabling IPv6 on an interface can generate more than the
514 # ND reply we are looking for (namely MLD). So loop through
515 # the replies to look for want we want.
Klement Sekeradab231a2016-12-21 08:50:14 +0100516 while now < deadline:
517 try:
518 captured_packet = pg_interface.wait_for_packet(
519 deadline - now, filter_out_fn=None)
520 except:
Klement Sekerada505f62017-01-04 12:58:53 +0100521 self.test.logger.error(
522 "Timeout while waiting for NDP response")
Klement Sekeradab231a2016-12-21 08:50:14 +0100523 raise
524 ndp_reply = captured_packet.copy() # keep original for exception
Neale Ranns82a06a92016-12-08 20:05:33 +0000525 try:
526 ndp_na = ndp_reply[ICMPv6ND_NA]
527 opt = ndp_na[ICMPv6NDOptDstLLAddr]
528 self.test.logger.info("VPP %s MAC address is %s " %
529 (self.name, opt.lladdr))
530 self._local_mac = opt.lladdr
Klement Sekeradab231a2016-12-21 08:50:14 +0100531 self.test.logger.debug(self.test.vapi.cli("show trace"))
532 # we now have the MAC we've been after
533 return
Neale Ranns82a06a92016-12-08 20:05:33 +0000534 except:
535 self.test.logger.info(
Klement Sekerada505f62017-01-04 12:58:53 +0100536 ppp("Unexpected response to NDP request:",
537 captured_packet))
Klement Sekeradab231a2016-12-21 08:50:14 +0100538 now = time.time()
539
540 self.test.logger.debug(self.test.vapi.cli("show trace"))
541 raise Exception("Timeout while waiting for NDP response")