blob: 2682774caabd2fcc2c52e01eb5df929dc21b4320 [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 Sekerad9b0c6f2022-04-26 19:02:15 +020016from scapy.layers.inet6 import (
17 IPv6,
18 ICMPv6ND_NS,
19 ICMPv6ND_NA,
20 ICMPv6NDOptSrcLLAddr,
21 ICMPv6NDOptDstLLAddr,
22 ICMPv6ND_RA,
23 RouterAlert,
24 IPv6ExtHdrHopByHop,
25)
Klement Sekera26cd0242022-02-18 10:35:08 +000026from util import ppp, ppc, UnexpectedPacketError
Neale Ranns75152282017-01-09 01:00:45 -080027from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
Klement Sekeraf62ae122016-10-11 11:47:09 +020028
Klement Sekerada505f62017-01-04 12:58:53 +010029
Klement Sekeraacb9b8e2017-02-14 02:55:31 +010030class CaptureTimeoutError(Exception):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020031 """Exception raised if capture or packet doesn't appear within timeout"""
32
Klement Sekeraacb9b8e2017-02-14 02:55:31 +010033 pass
34
35
Klement Sekera65cc8c02016-12-18 15:49:54 +010036def is_ipv6_misc(p):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020037 """Is packet one of uninteresting IPv6 broadcasts?"""
Klement Sekera65cc8c02016-12-18 15:49:54 +010038 if p.haslayer(ICMPv6ND_RA):
Neale Ranns75152282017-01-09 01:00:45 -080039 if in6_ismaddr(p[IPv6].dst):
40 return True
Klement Sekera65cc8c02016-12-18 15:49:54 +010041 if p.haslayer(IPv6ExtHdrHopByHop):
42 for o in p[IPv6ExtHdrHopByHop].options:
43 if isinstance(o, RouterAlert):
44 return True
45 return False
46
47
Klement Sekeraf62ae122016-10-11 11:47:09 +020048class VppPGInterface(VppInterface):
49 """
50 VPP packet-generator interface
51 """
52
53 @property
54 def pg_index(self):
55 """packet-generator interface index assigned by VPP"""
56 return self._pg_index
57
58 @property
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +020059 def gso_enabled(self):
60 """gso enabled on packet-generator interface"""
61 if self._gso_enabled == 0:
62 return "gso-disabled"
63 return "gso-enabled"
64
65 @property
66 def gso_size(self):
67 """gso size on packet-generator interface"""
68 return self._gso_size
69
70 @property
Mohsin Kazmif382b062020-08-11 15:00:44 +020071 def coalesce_is_enabled(self):
72 """coalesce enabled on packet-generator interface"""
73 if self._coalesce_enabled == 0:
74 return "coalesce-disabled"
75 return "coalesce-enabled"
76
77 @property
Klement Sekeraf62ae122016-10-11 11:47:09 +020078 def out_path(self):
79 """pcap file path - captured packets"""
80 return self._out_path
81
Klement Sekera7ba9fae2021-03-31 13:36:38 +020082 def get_in_path(self, worker):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020083 """pcap file path - injected packets"""
Klement Sekera7ba9fae2021-03-31 13:36:38 +020084 if worker is not None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020085 return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index, worker)
Klement Sekera7ba9fae2021-03-31 13:36:38 +020086 return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +020087
88 @property
89 def capture_cli(self):
90 """CLI string to start capture on this interface"""
91 return self._capture_cli
92
Klement Sekera7ba9fae2021-03-31 13:36:38 +020093 def get_cap_name(self, worker=None):
94 """return capture name for this interface and given worker"""
95 if worker is not None:
96 return self._cap_name + "-worker%d" % worker
Klement Sekeraf62ae122016-10-11 11:47:09 +020097 return self._cap_name
98
Klement Sekera7ba9fae2021-03-31 13:36:38 +020099 def get_input_cli(self, nb_replays=None, worker=None):
100 """return CLI string to load the injected packets"""
101 input_cli = "packet-generator new pcap %s source pg%u name %s" % (
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200102 self.get_in_path(worker),
103 self.pg_index,
104 self.get_cap_name(worker),
105 )
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200106 if nb_replays is not None:
107 return "%s limit %d" % (input_cli, nb_replays)
108 if worker is not None:
109 return "%s worker %d" % (input_cli, worker)
110 return input_cli
Klement Sekeraf62ae122016-10-11 11:47:09 +0200111
Klement Sekera778c2762016-11-08 02:00:28 +0100112 @property
113 def in_history_counter(self):
114 """Self-incrementing counter used when renaming old pcap files"""
115 v = self._in_history_counter
116 self._in_history_counter += 1
117 return v
118
119 @property
120 def out_history_counter(self):
121 """Self-incrementing counter used when renaming old pcap files"""
122 v = self._out_history_counter
123 self._out_history_counter += 1
124 return v
125
Neale Ranns6197cb72021-06-03 14:43:21 +0000126 def __init__(self, test, pg_index, gso, gso_size, mode):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200127 """Create VPP packet-generator interface"""
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200128 super().__init__(test)
Klement Sekeraa98346f2018-05-16 10:52:45 +0200129
Neale Ranns6197cb72021-06-03 14:43:21 +0000130 r = test.vapi.pg_create_interface_v2(pg_index, gso, gso_size, mode)
Klement Sekera31da2e32018-06-24 22:49:55 +0200131 self.set_sw_if_index(r.sw_if_index)
132
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100133 self._in_history_counter = 0
134 self._out_history_counter = 0
Klement Sekera97f6edc2017-01-12 07:17:01 +0100135 self._out_assert_counter = 0
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100136 self._pg_index = pg_index
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +0200137 self._gso_enabled = gso
138 self._gso_size = gso_size
Mohsin Kazmif382b062020-08-11 15:00:44 +0200139 self._coalesce_enabled = 0
Klement Sekera74dcdbf2016-11-14 09:49:09 +0100140 self._out_file = "pg%u_out.pcap" % self.pg_index
Klement Sekera778c2762016-11-08 02:00:28 +0100141 self._out_path = self.test.tempdir + "/" + self._out_file
Klement Sekeraf62ae122016-10-11 11:47:09 +0200142 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200143 self.pg_index,
144 self.out_path,
145 )
146 self._cap_name = "pcap%u-sw_if_index-%s" % (self.pg_index, self.sw_if_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200147
Klement Sekerab23ffd72021-05-31 16:08:53 +0200148 def handle_old_pcap_file(self, path, counter):
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200149 filename = os.path.basename(path)
Klement Sekerab23ffd72021-05-31 16:08:53 +0200150
151 if not config.keep_pcaps:
152 try:
153 self.test.logger.debug(f"Removing {path}")
154 os.remove(path)
155 except OSError:
156 self.test.logger.debug(f"OSError: Could not remove {path}")
157 return
158
159 # keep
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400160 try:
Klement Sekerab23ffd72021-05-31 16:08:53 +0200161
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400162 if os.path.isfile(path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200163 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % (
164 self.test.tempdir,
165 time.time(),
166 self.name,
167 counter,
168 filename,
169 )
Klement Sekerab23ffd72021-05-31 16:08:53 +0200170 self.test.logger.debug("Renaming %s->%s" % (path, name))
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400171 os.rename(path, name)
172 except OSError:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200173 self.test.logger.debug("OSError: Could not rename %s %s" % (path, filename))
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400174
Klement Sekerada505f62017-01-04 12:58:53 +0100175 def enable_capture(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200176 """Enable capture on this packet-generator interface
177 of at most n packets.
178 If n < 0, this is no limit
Alexandre Poirriera618e202019-05-07 10:43:41 +0200179 """
Andrew Yourtchenkocb265c62019-07-25 10:03:51 +0000180 # disable the capture to flush the capture
181 self.disable_capture()
Klement Sekerab23ffd72021-05-31 16:08:53 +0200182 self.handle_old_pcap_file(self.out_path, self.out_history_counter)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200183 # FIXME this should be an API, but no such exists atm
184 self.test.vapi.cli(self.capture_cli)
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200185 self._pcap_reader = None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200186
Alexandre Poirriera618e202019-05-07 10:43:41 +0200187 def disable_capture(self):
188 self.test.vapi.cli("%s disable" % self.capture_cli)
189
Mohsin Kazmif382b062020-08-11 15:00:44 +0200190 def coalesce_enable(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200191 """Enable packet coalesce on this packet-generator interface"""
Mohsin Kazmif382b062020-08-11 15:00:44 +0200192 self._coalesce_enabled = 1
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200193 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 1)
Mohsin Kazmif382b062020-08-11 15:00:44 +0200194
195 def coalesce_disable(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200196 """Disable packet coalesce on this packet-generator interface"""
Mohsin Kazmif382b062020-08-11 15:00:44 +0200197 self._coalesce_enabled = 0
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200198 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 0)
Mohsin Kazmif382b062020-08-11 15:00:44 +0200199
Klement Sekera4ecbf102019-07-31 13:14:16 +0000200 def add_stream(self, pkts, nb_replays=None, worker=None):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200201 """
202 Add a stream of packets to this packet-generator
203
204 :param pkts: iterable packets
205
206 """
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200207 wrpcap(self.get_in_path(worker), pkts)
Klement Sekera3ff6ffc2021-04-01 18:19:29 +0200208 self.test.register_pcap(self, worker)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200209 # FIXME this should be an API, but no such exists atm
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200210 self.test.vapi.cli(self.get_input_cli(nb_replays, worker))
Klement Sekeraf62ae122016-10-11 11:47:09 +0200211
Klement Sekera97f6edc2017-01-12 07:17:01 +0100212 def generate_debug_aid(self, kind):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200213 """Create a hardlink to the out file with a counter and a file
Klement Sekera97f6edc2017-01-12 07:17:01 +0100214 containing stack trace to ease debugging in case of multiple capture
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200215 files present."""
216 self.test.logger.debug("Generating debug aid for %s on %s" % (kind, self._name))
217 link_path, stack_path = [
218 "%s/debug_%s_%s_%s.%s"
219 % (self.test.tempdir, self._name, self._out_assert_counter, kind, suffix)
220 for suffix in ["pcap", "stack"]
221 ]
Klement Sekera97f6edc2017-01-12 07:17:01 +0100222 os.link(self.out_path, link_path)
223 with open(stack_path, "w") as f:
224 f.writelines(format_stack())
225 self._out_assert_counter += 1
226
Klement Sekeradab231a2016-12-21 08:50:14 +0100227 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200228 """Helper method to get capture and filter it"""
Klement Sekeraf62ae122016-10-11 11:47:09 +0200229 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100230 if not self.wait_for_capture_file(timeout):
231 return None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200232 output = rdpcap(self.out_path)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100233 self.test.logger.debug("Capture has %s packets" % len(output.res))
Klement Sekeradab231a2016-12-21 08:50:14 +0100234 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200235 self.test.logger.debug(
236 "Exception in scapy.rdpcap (%s): %s" % (self.out_path, format_exc())
237 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100238 return None
Klement Sekera65cc8c02016-12-18 15:49:54 +0100239 before = len(output.res)
Klement Sekeradab231a2016-12-21 08:50:14 +0100240 if filter_out_fn:
241 output.res = [p for p in output.res if not filter_out_fn(p)]
Klement Sekera97f6edc2017-01-12 07:17:01 +0100242 removed = before - len(output.res)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100243 if removed:
244 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200245 "Filtered out %s packets from capture (returning %s)"
246 % (removed, len(output.res))
247 )
Klement Sekeraf62ae122016-10-11 11:47:09 +0200248 return output
Matej Klotton0178d522016-11-04 11:11:44 +0100249
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200250 def get_capture(
251 self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc
252 ):
253 """Get captured packets
Klement Sekeradab231a2016-12-21 08:50:14 +0100254
255 :param expected_count: expected number of packets to capture, if None,
256 then self.test.packet_count_for_dst_pg_idx is
257 used to lookup the expected count
258 :param remark: remark printed into debug logs
259 :param timeout: how long to wait for packets
260 :param filter_out_fn: filter applied to each packet, packets for which
261 the filter returns True are removed from capture
262 :returns: iterable packets
263 """
264 remaining_time = timeout
265 capture = None
266 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
267 based_on = "based on provided argument"
268 if expected_count is None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200269 expected_count = self.test.get_packet_count_for_if_idx(self.sw_if_index)
Klement Sekeradab231a2016-12-21 08:50:14 +0100270 based_on = "based on stored packet_infos"
Klement Sekerac86fa022017-01-02 09:03:47 +0100271 if expected_count == 0:
272 raise Exception(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200273 "Internal error, expected packet count for %s is 0!" % name
274 )
275 self.test.logger.debug(
276 "Expecting to capture %s (%s) packets on %s"
277 % (expected_count, based_on, name)
278 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100279 while remaining_time > 0:
280 before = time.time()
281 capture = self._get_capture(remaining_time, filter_out_fn)
282 elapsed_time = time.time() - before
283 if capture:
284 if len(capture.res) == expected_count:
285 # bingo, got the packets we expected
286 return capture
Jan Gelety057bb8c2016-12-20 17:32:45 +0100287 elif len(capture.res) > expected_count:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200288 self.test.logger.error(ppc("Unexpected packets captured:", capture))
Jan Gelety057bb8c2016-12-20 17:32:45 +0100289 break
Klement Sekera97f6edc2017-01-12 07:17:01 +0100290 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200291 self.test.logger.debug(
292 "Partial capture containing %s "
293 "packets doesn't match expected "
294 "count %s (yet?)" % (len(capture.res), expected_count)
295 )
Klement Sekera97f6edc2017-01-12 07:17:01 +0100296 elif expected_count == 0:
297 # bingo, got None as we expected - return empty capture
298 return PacketList()
Klement Sekeradab231a2016-12-21 08:50:14 +0100299 remaining_time -= elapsed_time
300 if capture:
Klement Sekera97f6edc2017-01-12 07:17:01 +0100301 self.generate_debug_aid("count-mismatch")
Klement Sekera26cd0242022-02-18 10:35:08 +0000302 if len(capture) > 0 and 0 == expected_count:
303 rem = f"\n{remark}" if remark else ""
304 raise UnexpectedPacketError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200305 capture[0], f"\n({len(capture)} packets captured in total){rem}"
306 )
307 raise Exception(
308 "Captured packets mismatch, captured %s packets, "
309 "expected %s packets on %s" % (len(capture.res), expected_count, name)
310 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100311 else:
Klement Sekera16ce09d2022-04-23 11:34:29 +0200312 if 0 == expected_count:
313 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100314 raise Exception("No packets captured on %s" % name)
315
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200316 def assert_nothing_captured(
317 self, timeout=1, remark=None, filter_out_fn=is_ipv6_misc
318 ):
319 """Assert that nothing unfiltered was captured on interface
Klement Sekeradab231a2016-12-21 08:50:14 +0100320
321 :param remark: remark printed into debug logs
322 :param filter_out_fn: filter applied to each packet, packets for which
323 the filter returns True are removed from capture
324 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200325 capture = self.get_capture(
326 0, timeout=timeout, remark=remark, filter_out_fn=filter_out_fn
327 )
Klement Sekera16ce09d2022-04-23 11:34:29 +0200328 if not capture or len(capture.res) == 0:
329 # junk filtered out, we're good
330 return
Klement Sekera9225dee2016-12-12 08:36:58 +0100331
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000332 def wait_for_pg_stop(self):
333 # wait till packet-generator is stopped
334 # "show packet-generator" while it is still running gives this:
335 # Name Enabled Count Parameters
336 # pcap0-sw_if_inde Yes 64 limit 64, ...
337 #
338 # also have a 5-minute timeout just in case things go terribly wrong...
339 deadline = time.time() + 300
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200340 while self.test.vapi.cli("show packet-generator").find("Yes") != -1:
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000341 self._test.sleep(0.01) # yield
342 if time.time() > deadline:
343 self.test.logger.debug("Timeout waiting for pg to stop")
344 break
345
Klement Sekera9225dee2016-12-12 08:36:58 +0100346 def wait_for_capture_file(self, timeout=1):
347 """
348 Wait until pcap capture file appears
349
350 :param timeout: How long to wait for the packet (default 1s)
351
Klement Sekeradab231a2016-12-21 08:50:14 +0100352 :returns: True/False if the file is present or appears within timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100353 """
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000354 self.wait_for_pg_stop()
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100355 deadline = time.time() + timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100356 if not os.path.isfile(self.out_path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200357 self.test.logger.debug(
358 "Waiting for capture file %s to appear, "
359 "timeout is %ss" % (self.out_path, timeout)
360 )
Klement Sekera9225dee2016-12-12 08:36:58 +0100361 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200362 self.test.logger.debug("Capture file %s already exists" % self.out_path)
Klement Sekeradab231a2016-12-21 08:50:14 +0100363 return True
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100364 while time.time() < deadline:
Klement Sekera9225dee2016-12-12 08:36:58 +0100365 if os.path.isfile(self.out_path):
366 break
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700367 self._test.sleep(0) # yield
Klement Sekera9225dee2016-12-12 08:36:58 +0100368 if os.path.isfile(self.out_path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200369 self.test.logger.debug(
370 "Capture file appeared after %fs" % (time.time() - (deadline - timeout))
371 )
Klement Sekera9225dee2016-12-12 08:36:58 +0100372 else:
373 self.test.logger.debug("Timeout - capture file still nowhere")
Klement Sekeradab231a2016-12-21 08:50:14 +0100374 return False
375 return True
Klement Sekera9225dee2016-12-12 08:36:58 +0100376
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100377 def verify_enough_packet_data_in_pcap(self):
Klement Sekerab91017a2017-02-09 06:04:36 +0100378 """
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100379 Check if enough data is available in file handled by internal pcap
380 reader so that a whole packet can be read.
Klement Sekerab91017a2017-02-09 06:04:36 +0100381
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100382 :returns: True if enough data present, else False
Klement Sekerab91017a2017-02-09 06:04:36 +0100383 """
384 orig_pos = self._pcap_reader.f.tell() # save file position
385 enough_data = False
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100386 # read packet header from pcap
387 packet_header_size = 16
388 caplen = None
389 end_pos = None
390 hdr = self._pcap_reader.f.read(packet_header_size)
391 if len(hdr) == packet_header_size:
392 # parse the capture length - caplen
Klement Sekerab91017a2017-02-09 06:04:36 +0100393 sec, usec, caplen, wirelen = struct.unpack(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200394 self._pcap_reader.endian + "IIII", hdr
395 )
Klement Sekerab91017a2017-02-09 06:04:36 +0100396 self._pcap_reader.f.seek(0, 2) # seek to end of file
397 end_pos = self._pcap_reader.f.tell() # get position at end
398 if end_pos >= orig_pos + len(hdr) + caplen:
399 enough_data = True # yay, we have enough data
Klement Sekerab91017a2017-02-09 06:04:36 +0100400 self._pcap_reader.f.seek(orig_pos, 0) # restore original position
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100401 return enough_data
Klement Sekerab91017a2017-02-09 06:04:36 +0100402
Klement Sekeradab231a2016-12-21 08:50:14 +0100403 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200404 """
405 Wait for next packet captured with a timeout
406
407 :param timeout: How long to wait for the packet
408
409 :returns: Captured packet if no packet arrived within timeout
410 :raises Exception: if no packet arrives within timeout
411 """
Klement Sekeradab231a2016-12-21 08:50:14 +0100412 deadline = time.time() + timeout
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200413 if self._pcap_reader is None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100414 if not self.wait_for_capture_file(timeout):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200415 raise CaptureTimeoutError(
416 "Capture file %s did not appear within timeout" % self.out_path
417 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100418 while time.time() < deadline:
419 try:
420 self._pcap_reader = PcapReader(self.out_path)
421 break
422 except:
Klement Sekerada505f62017-01-04 12:58:53 +0100423 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200424 "Exception in scapy.PcapReader(%s): %s"
425 % (self.out_path, format_exc())
426 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100427 if not self._pcap_reader:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200428 raise CaptureTimeoutError(
429 "Capture file %s did not appear within timeout" % self.out_path
430 )
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200431
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100432 poll = False
433 if timeout > 0:
434 self.test.logger.debug("Waiting for packet")
435 else:
436 poll = True
437 self.test.logger.debug("Polling for packet")
438 while time.time() < deadline or poll:
439 if not self.verify_enough_packet_data_in_pcap():
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700440 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100441 poll = False
442 continue
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200443 p = self._pcap_reader.recv()
444 if p is not None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100445 if filter_out_fn is not None and filter_out_fn(p):
446 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200447 "Packet received after %ss was filtered out"
448 % (time.time() - (deadline - timeout))
449 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100450 else:
Klement Sekerada505f62017-01-04 12:58:53 +0100451 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200452 "Packet received after %fs"
453 % (time.time() - (deadline - timeout))
454 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100455 return p
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700456 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100457 poll = False
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200458 self.test.logger.debug("Timeout - no packets received")
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100459 raise CaptureTimeoutError("Packet didn't arrive within timeout")
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200460
Matej Klotton0178d522016-11-04 11:11:44 +0100461 def create_arp_req(self):
462 """Create ARP request applicable for this interface"""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200463 return Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) / ARP(
464 op=ARP.who_has,
465 pdst=self.local_ip4,
466 psrc=self.remote_ip4,
467 hwsrc=self.remote_mac,
468 )
Matej Klotton0178d522016-11-04 11:11:44 +0100469
Benoît Ganne2699fe22021-01-18 19:25:38 +0100470 def create_ndp_req(self, addr=None):
Matej Klotton0178d522016-11-04 11:11:44 +0100471 """Create NDP - NS applicable for this interface"""
Benoît Ganne2699fe22021-01-18 19:25:38 +0100472 if not addr:
473 addr = self.local_ip6
474 nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr))
Neale Ranns465a1a32017-01-07 10:04:09 -0800475 d = inet_ntop(socket.AF_INET6, nsma)
476
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200477 return (
478 Ether(dst=in6_getnsmac(nsma))
479 / IPv6(dst=d, src=self.remote_ip6)
480 / ICMPv6ND_NS(tgt=addr)
481 / ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac)
482 )
Matej Klotton0178d522016-11-04 11:11:44 +0100483
484 def resolve_arp(self, pg_interface=None):
485 """Resolve ARP using provided packet-generator interface
486
487 :param pg_interface: interface used to resolve, if None then this
488 interface is used
489
490 """
491 if pg_interface is None:
492 pg_interface = self
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200493 self.test.logger.info(
494 "Sending ARP request for %s on port %s"
495 % (self.local_ip4, pg_interface.name)
496 )
Matej Klotton0178d522016-11-04 11:11:44 +0100497 arp_req = self.create_arp_req()
498 pg_interface.add_stream(arp_req)
499 pg_interface.enable_capture()
500 self.test.pg_start()
Klement Sekera7bb873a2016-11-18 07:38:42 +0100501 self.test.logger.info(self.test.vapi.cli("show trace"))
Klement Sekera9225dee2016-12-12 08:36:58 +0100502 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100503 captured_packet = pg_interface.wait_for_packet(1)
Klement Sekera9225dee2016-12-12 08:36:58 +0100504 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200505 self.test.logger.info("No ARP received on port %s" % pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100506 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100507 arp_reply = captured_packet.copy() # keep original for exception
Matej Klotton0178d522016-11-04 11:11:44 +0100508 try:
509 if arp_reply[ARP].op == ARP.is_at:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200510 self.test.logger.info(
511 "VPP %s MAC address is %s " % (self.name, arp_reply[ARP].hwsrc)
512 )
Matej Klotton0178d522016-11-04 11:11:44 +0100513 self._local_mac = arp_reply[ARP].hwsrc
514 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200515 self.test.logger.info("No ARP received on port %s" % pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100516 except:
Klement Sekera7bb873a2016-11-18 07:38:42 +0100517 self.test.logger.error(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200518 ppp("Unexpected response to ARP request:", captured_packet)
519 )
Matej Klotton0178d522016-11-04 11:11:44 +0100520 raise
521
Benoît Ganne2699fe22021-01-18 19:25:38 +0100522 def resolve_ndp(self, pg_interface=None, timeout=1, link_layer=False):
Matej Klotton0178d522016-11-04 11:11:44 +0100523 """Resolve NDP using provided packet-generator interface
524
525 :param pg_interface: interface used to resolve, if None then this
526 interface is used
Klement Sekeradab231a2016-12-21 08:50:14 +0100527 :param timeout: how long to wait for response before giving up
Benoît Ganne2699fe22021-01-18 19:25:38 +0100528 :param link_layer: resolve for global address if False (default)
529 or for link-layer address if True
Matej Klotton0178d522016-11-04 11:11:44 +0100530
531 """
532 if pg_interface is None:
533 pg_interface = self
Benoît Ganne2699fe22021-01-18 19:25:38 +0100534 addr = self.local_ip6_ll if link_layer else self.local_ip6
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200535 self.test.logger.info(
536 "Sending NDP request for %s on port %s" % (addr, pg_interface.name)
537 )
Benoît Ganne2699fe22021-01-18 19:25:38 +0100538 ndp_req = self.create_ndp_req(addr)
Matej Klotton0178d522016-11-04 11:11:44 +0100539 pg_interface.add_stream(ndp_req)
540 pg_interface.enable_capture()
541 self.test.pg_start()
Klement Sekeradab231a2016-12-21 08:50:14 +0100542 now = time.time()
543 deadline = now + timeout
Neale Ranns82a06a92016-12-08 20:05:33 +0000544 # Enabling IPv6 on an interface can generate more than the
545 # ND reply we are looking for (namely MLD). So loop through
546 # the replies to look for want we want.
Klement Sekeradab231a2016-12-21 08:50:14 +0100547 while now < deadline:
548 try:
549 captured_packet = pg_interface.wait_for_packet(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200550 deadline - now, filter_out_fn=None
551 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100552 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200553 self.test.logger.error("Timeout while waiting for NDP response")
Klement Sekeradab231a2016-12-21 08:50:14 +0100554 raise
555 ndp_reply = captured_packet.copy() # keep original for exception
Neale Ranns82a06a92016-12-08 20:05:33 +0000556 try:
557 ndp_na = ndp_reply[ICMPv6ND_NA]
558 opt = ndp_na[ICMPv6NDOptDstLLAddr]
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200559 self.test.logger.info(
560 "VPP %s MAC address is %s " % (self.name, opt.lladdr)
561 )
Neale Ranns82a06a92016-12-08 20:05:33 +0000562 self._local_mac = opt.lladdr
Klement Sekeradab231a2016-12-21 08:50:14 +0100563 self.test.logger.debug(self.test.vapi.cli("show trace"))
564 # we now have the MAC we've been after
565 return
Neale Ranns82a06a92016-12-08 20:05:33 +0000566 except:
567 self.test.logger.info(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200568 ppp("Unexpected response to NDP request:", captured_packet)
569 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100570 now = time.time()
571
572 self.test.logger.debug(self.test.vapi.cli("show trace"))
573 raise Exception("Timeout while waiting for NDP response")