blob: 0fd5df4f345495a40f423503fb002df4313e34ef [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
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -07008
Klement Sekerab23ffd72021-05-31 16:08:53 +02009from config import config
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -070010import scapy.compat
Klement Sekera0e3c0de2016-09-29 14:43:44 +020011from scapy.utils import wrpcap, rdpcap, PcapReader
Klement Sekera97f6edc2017-01-12 07:17:01 +010012from scapy.plist import PacketList
Klement Sekeraf62ae122016-10-11 11:47:09 +020013from vpp_interface import VppInterface
Neale Ranns6197cb72021-06-03 14:43:21 +000014from vpp_papi import VppEnum
Klement Sekeraf62ae122016-10-11 11:47:09 +020015
Matej Klotton0178d522016-11-04 11:11:44 +010016from scapy.layers.l2 import Ether, ARP
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020017from scapy.layers.inet6 import (
18 IPv6,
19 ICMPv6ND_NS,
20 ICMPv6ND_NA,
21 ICMPv6NDOptSrcLLAddr,
22 ICMPv6NDOptDstLLAddr,
23 ICMPv6ND_RA,
24 RouterAlert,
25 IPv6ExtHdrHopByHop,
26)
Klement Sekera26cd0242022-02-18 10:35:08 +000027from util import ppp, ppc, UnexpectedPacketError
Neale Ranns75152282017-01-09 01:00:45 -080028from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
Klement Sekeraf62ae122016-10-11 11:47:09 +020029
Klement Sekerada505f62017-01-04 12:58:53 +010030
Klement Sekeraacb9b8e2017-02-14 02:55:31 +010031class CaptureTimeoutError(Exception):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020032 """Exception raised if capture or packet doesn't appear within timeout"""
33
Klement Sekeraacb9b8e2017-02-14 02:55:31 +010034 pass
35
36
Klement Sekera65cc8c02016-12-18 15:49:54 +010037def is_ipv6_misc(p):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020038 """Is packet one of uninteresting IPv6 broadcasts?"""
Klement Sekera65cc8c02016-12-18 15:49:54 +010039 if p.haslayer(ICMPv6ND_RA):
Neale Ranns75152282017-01-09 01:00:45 -080040 if in6_ismaddr(p[IPv6].dst):
41 return True
Klement Sekera65cc8c02016-12-18 15:49:54 +010042 if p.haslayer(IPv6ExtHdrHopByHop):
43 for o in p[IPv6ExtHdrHopByHop].options:
44 if isinstance(o, RouterAlert):
45 return True
46 return False
47
48
Klement Sekeraf62ae122016-10-11 11:47:09 +020049class VppPGInterface(VppInterface):
50 """
51 VPP packet-generator interface
52 """
53
54 @property
55 def pg_index(self):
56 """packet-generator interface index assigned by VPP"""
57 return self._pg_index
58
59 @property
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +020060 def gso_enabled(self):
61 """gso enabled on packet-generator interface"""
62 if self._gso_enabled == 0:
63 return "gso-disabled"
64 return "gso-enabled"
65
66 @property
67 def gso_size(self):
68 """gso size on packet-generator interface"""
69 return self._gso_size
70
71 @property
Mohsin Kazmif382b062020-08-11 15:00:44 +020072 def coalesce_is_enabled(self):
73 """coalesce enabled on packet-generator interface"""
74 if self._coalesce_enabled == 0:
75 return "coalesce-disabled"
76 return "coalesce-enabled"
77
78 @property
Klement Sekeraf62ae122016-10-11 11:47:09 +020079 def out_path(self):
80 """pcap file path - captured packets"""
81 return self._out_path
82
Klement Sekera7ba9fae2021-03-31 13:36:38 +020083 def get_in_path(self, worker):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020084 """pcap file path - injected packets"""
Klement Sekera7ba9fae2021-03-31 13:36:38 +020085 if worker is not None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020086 return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index, worker)
Klement Sekera7ba9fae2021-03-31 13:36:38 +020087 return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +020088
89 @property
90 def capture_cli(self):
91 """CLI string to start capture on this interface"""
92 return self._capture_cli
93
Klement Sekera7ba9fae2021-03-31 13:36:38 +020094 def get_cap_name(self, worker=None):
95 """return capture name for this interface and given worker"""
96 if worker is not None:
97 return self._cap_name + "-worker%d" % worker
Klement Sekeraf62ae122016-10-11 11:47:09 +020098 return self._cap_name
99
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200100 def get_input_cli(self, nb_replays=None, worker=None):
101 """return CLI string to load the injected packets"""
102 input_cli = "packet-generator new pcap %s source pg%u name %s" % (
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200103 self.get_in_path(worker),
104 self.pg_index,
105 self.get_cap_name(worker),
106 )
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200107 if nb_replays is not None:
108 return "%s limit %d" % (input_cli, nb_replays)
109 if worker is not None:
110 return "%s worker %d" % (input_cli, worker)
111 return input_cli
Klement Sekeraf62ae122016-10-11 11:47:09 +0200112
Klement Sekera778c2762016-11-08 02:00:28 +0100113 @property
114 def in_history_counter(self):
115 """Self-incrementing counter used when renaming old pcap files"""
116 v = self._in_history_counter
117 self._in_history_counter += 1
118 return v
119
120 @property
121 def out_history_counter(self):
122 """Self-incrementing counter used when renaming old pcap files"""
123 v = self._out_history_counter
124 self._out_history_counter += 1
125 return v
126
Neale Ranns6197cb72021-06-03 14:43:21 +0000127 def __init__(self, test, pg_index, gso, gso_size, mode):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200128 """Create VPP packet-generator interface"""
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200129 super().__init__(test)
Klement Sekeraa98346f2018-05-16 10:52:45 +0200130
Neale Ranns6197cb72021-06-03 14:43:21 +0000131 r = test.vapi.pg_create_interface_v2(pg_index, gso, gso_size, mode)
Klement Sekera31da2e32018-06-24 22:49:55 +0200132 self.set_sw_if_index(r.sw_if_index)
133
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100134 self._in_history_counter = 0
135 self._out_history_counter = 0
Klement Sekera97f6edc2017-01-12 07:17:01 +0100136 self._out_assert_counter = 0
Matej Klottonc5bf07f2016-11-23 15:27:17 +0100137 self._pg_index = pg_index
Mohsin Kazmi22e9cfd2019-07-23 11:54:48 +0200138 self._gso_enabled = gso
139 self._gso_size = gso_size
Mohsin Kazmif382b062020-08-11 15:00:44 +0200140 self._coalesce_enabled = 0
Klement Sekera74dcdbf2016-11-14 09:49:09 +0100141 self._out_file = "pg%u_out.pcap" % self.pg_index
Klement Sekera778c2762016-11-08 02:00:28 +0100142 self._out_path = self.test.tempdir + "/" + self._out_file
Klement Sekeraf62ae122016-10-11 11:47:09 +0200143 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200144 self.pg_index,
145 self.out_path,
146 )
147 self._cap_name = "pcap%u-sw_if_index-%s" % (self.pg_index, self.sw_if_index)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200148
Klement Sekerab23ffd72021-05-31 16:08:53 +0200149 def handle_old_pcap_file(self, path, counter):
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200150 filename = os.path.basename(path)
Klement Sekerab23ffd72021-05-31 16:08:53 +0200151
152 if not config.keep_pcaps:
153 try:
154 self.test.logger.debug(f"Removing {path}")
155 os.remove(path)
156 except OSError:
157 self.test.logger.debug(f"OSError: Could not remove {path}")
158 return
159
160 # keep
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400161 try:
Klement Sekerab23ffd72021-05-31 16:08:53 +0200162
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400163 if os.path.isfile(path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200164 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % (
165 self.test.tempdir,
166 time.time(),
167 self.name,
168 counter,
169 filename,
170 )
Klement Sekerab23ffd72021-05-31 16:08:53 +0200171 self.test.logger.debug("Renaming %s->%s" % (path, name))
Dmitry Valter71d02aa2023-01-27 12:49:55 +0000172 shutil.move(path, name)
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400173 except OSError:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200174 self.test.logger.debug("OSError: Could not rename %s %s" % (path, filename))
Paul Vinciguerra4b58a862019-05-28 15:40:47 -0400175
Klement Sekerada505f62017-01-04 12:58:53 +0100176 def enable_capture(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200177 """Enable capture on this packet-generator interface
178 of at most n packets.
179 If n < 0, this is no limit
Alexandre Poirriera618e202019-05-07 10:43:41 +0200180 """
Andrew Yourtchenkocb265c62019-07-25 10:03:51 +0000181 # disable the capture to flush the capture
182 self.disable_capture()
Klement Sekerab23ffd72021-05-31 16:08:53 +0200183 self.handle_old_pcap_file(self.out_path, self.out_history_counter)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200184 # FIXME this should be an API, but no such exists atm
185 self.test.vapi.cli(self.capture_cli)
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200186 self._pcap_reader = None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200187
Alexandre Poirriera618e202019-05-07 10:43:41 +0200188 def disable_capture(self):
189 self.test.vapi.cli("%s disable" % self.capture_cli)
190
Mohsin Kazmif382b062020-08-11 15:00:44 +0200191 def coalesce_enable(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200192 """Enable packet coalesce on this packet-generator interface"""
Mohsin Kazmif382b062020-08-11 15:00:44 +0200193 self._coalesce_enabled = 1
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200194 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 1)
Mohsin Kazmif382b062020-08-11 15:00:44 +0200195
196 def coalesce_disable(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200197 """Disable packet coalesce on this packet-generator interface"""
Mohsin Kazmif382b062020-08-11 15:00:44 +0200198 self._coalesce_enabled = 0
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200199 self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 0)
Mohsin Kazmif382b062020-08-11 15:00:44 +0200200
Klement Sekera4ecbf102019-07-31 13:14:16 +0000201 def add_stream(self, pkts, nb_replays=None, worker=None):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200202 """
203 Add a stream of packets to this packet-generator
204
205 :param pkts: iterable packets
206
207 """
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200208 wrpcap(self.get_in_path(worker), pkts)
Klement Sekera3ff6ffc2021-04-01 18:19:29 +0200209 self.test.register_pcap(self, worker)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200210 # FIXME this should be an API, but no such exists atm
Klement Sekera7ba9fae2021-03-31 13:36:38 +0200211 self.test.vapi.cli(self.get_input_cli(nb_replays, worker))
Klement Sekeraf62ae122016-10-11 11:47:09 +0200212
Klement Sekera97f6edc2017-01-12 07:17:01 +0100213 def generate_debug_aid(self, kind):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200214 """Create a hardlink to the out file with a counter and a file
Klement Sekera97f6edc2017-01-12 07:17:01 +0100215 containing stack trace to ease debugging in case of multiple capture
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200216 files present."""
217 self.test.logger.debug("Generating debug aid for %s on %s" % (kind, self._name))
218 link_path, stack_path = [
219 "%s/debug_%s_%s_%s.%s"
220 % (self.test.tempdir, self._name, self._out_assert_counter, kind, suffix)
221 for suffix in ["pcap", "stack"]
222 ]
Klement Sekera97f6edc2017-01-12 07:17:01 +0100223 os.link(self.out_path, link_path)
224 with open(stack_path, "w") as f:
225 f.writelines(format_stack())
226 self._out_assert_counter += 1
227
Klement Sekeradab231a2016-12-21 08:50:14 +0100228 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200229 """Helper method to get capture and filter it"""
Klement Sekeraf62ae122016-10-11 11:47:09 +0200230 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100231 if not self.wait_for_capture_file(timeout):
232 return None
Klement Sekeraf62ae122016-10-11 11:47:09 +0200233 output = rdpcap(self.out_path)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100234 self.test.logger.debug("Capture has %s packets" % len(output.res))
Klement Sekeradab231a2016-12-21 08:50:14 +0100235 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200236 self.test.logger.debug(
237 "Exception in scapy.rdpcap (%s): %s" % (self.out_path, format_exc())
238 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100239 return None
Klement Sekera65cc8c02016-12-18 15:49:54 +0100240 before = len(output.res)
Klement Sekeradab231a2016-12-21 08:50:14 +0100241 if filter_out_fn:
242 output.res = [p for p in output.res if not filter_out_fn(p)]
Klement Sekera97f6edc2017-01-12 07:17:01 +0100243 removed = before - len(output.res)
Klement Sekera65cc8c02016-12-18 15:49:54 +0100244 if removed:
245 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200246 "Filtered out %s packets from capture (returning %s)"
247 % (removed, len(output.res))
248 )
Klement Sekeraf62ae122016-10-11 11:47:09 +0200249 return output
Matej Klotton0178d522016-11-04 11:11:44 +0100250
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200251 def get_capture(
252 self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc
253 ):
254 """Get captured packets
Klement Sekeradab231a2016-12-21 08:50:14 +0100255
256 :param expected_count: expected number of packets to capture, if None,
257 then self.test.packet_count_for_dst_pg_idx is
258 used to lookup the expected count
259 :param remark: remark printed into debug logs
260 :param timeout: how long to wait for packets
261 :param filter_out_fn: filter applied to each packet, packets for which
262 the filter returns True are removed from capture
263 :returns: iterable packets
264 """
265 remaining_time = timeout
266 capture = None
267 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
268 based_on = "based on provided argument"
269 if expected_count is None:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200270 expected_count = self.test.get_packet_count_for_if_idx(self.sw_if_index)
Klement Sekeradab231a2016-12-21 08:50:14 +0100271 based_on = "based on stored packet_infos"
Klement Sekerac86fa022017-01-02 09:03:47 +0100272 if expected_count == 0:
273 raise Exception(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200274 "Internal error, expected packet count for %s is 0!" % name
275 )
276 self.test.logger.debug(
277 "Expecting to capture %s (%s) packets on %s"
278 % (expected_count, based_on, name)
279 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100280 while remaining_time > 0:
281 before = time.time()
282 capture = self._get_capture(remaining_time, filter_out_fn)
283 elapsed_time = time.time() - before
284 if capture:
285 if len(capture.res) == expected_count:
286 # bingo, got the packets we expected
287 return capture
Jan Gelety057bb8c2016-12-20 17:32:45 +0100288 elif len(capture.res) > expected_count:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200289 self.test.logger.error(ppc("Unexpected packets captured:", capture))
Jan Gelety057bb8c2016-12-20 17:32:45 +0100290 break
Klement Sekera97f6edc2017-01-12 07:17:01 +0100291 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200292 self.test.logger.debug(
293 "Partial capture containing %s "
294 "packets doesn't match expected "
295 "count %s (yet?)" % (len(capture.res), expected_count)
296 )
Klement Sekera97f6edc2017-01-12 07:17:01 +0100297 elif expected_count == 0:
298 # bingo, got None as we expected - return empty capture
299 return PacketList()
Klement Sekeradab231a2016-12-21 08:50:14 +0100300 remaining_time -= elapsed_time
301 if capture:
Klement Sekera97f6edc2017-01-12 07:17:01 +0100302 self.generate_debug_aid("count-mismatch")
Klement Sekera26cd0242022-02-18 10:35:08 +0000303 if len(capture) > 0 and 0 == expected_count:
304 rem = f"\n{remark}" if remark else ""
305 raise UnexpectedPacketError(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200306 capture[0], f"\n({len(capture)} packets captured in total){rem}"
307 )
308 raise Exception(
309 "Captured packets mismatch, captured %s packets, "
310 "expected %s packets on %s" % (len(capture.res), expected_count, name)
311 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100312 else:
Klement Sekera16ce09d2022-04-23 11:34:29 +0200313 if 0 == expected_count:
314 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100315 raise Exception("No packets captured on %s" % name)
316
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200317 def assert_nothing_captured(
318 self, timeout=1, remark=None, filter_out_fn=is_ipv6_misc
319 ):
320 """Assert that nothing unfiltered was captured on interface
Klement Sekeradab231a2016-12-21 08:50:14 +0100321
322 :param remark: remark printed into debug logs
323 :param filter_out_fn: filter applied to each packet, packets for which
324 the filter returns True are removed from capture
325 """
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200326 capture = self.get_capture(
327 0, timeout=timeout, remark=remark, filter_out_fn=filter_out_fn
328 )
Klement Sekera16ce09d2022-04-23 11:34:29 +0200329 if not capture or len(capture.res) == 0:
330 # junk filtered out, we're good
331 return
Klement Sekera9225dee2016-12-12 08:36:58 +0100332
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000333 def wait_for_pg_stop(self):
334 # wait till packet-generator is stopped
335 # "show packet-generator" while it is still running gives this:
336 # Name Enabled Count Parameters
337 # pcap0-sw_if_inde Yes 64 limit 64, ...
338 #
339 # also have a 5-minute timeout just in case things go terribly wrong...
340 deadline = time.time() + 300
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200341 while self.test.vapi.cli("show packet-generator").find("Yes") != -1:
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000342 self._test.sleep(0.01) # yield
343 if time.time() > deadline:
344 self.test.logger.debug("Timeout waiting for pg to stop")
345 break
346
Klement Sekera9225dee2016-12-12 08:36:58 +0100347 def wait_for_capture_file(self, timeout=1):
348 """
349 Wait until pcap capture file appears
350
351 :param timeout: How long to wait for the packet (default 1s)
352
Klement Sekeradab231a2016-12-21 08:50:14 +0100353 :returns: True/False if the file is present or appears within timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100354 """
Andrew Yourtchenko3d36f192019-10-11 12:34:12 +0000355 self.wait_for_pg_stop()
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100356 deadline = time.time() + timeout
Klement Sekera9225dee2016-12-12 08:36:58 +0100357 if not os.path.isfile(self.out_path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200358 self.test.logger.debug(
359 "Waiting for capture file %s to appear, "
360 "timeout is %ss" % (self.out_path, timeout)
361 )
Klement Sekera9225dee2016-12-12 08:36:58 +0100362 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200363 self.test.logger.debug("Capture file %s already exists" % self.out_path)
Klement Sekeradab231a2016-12-21 08:50:14 +0100364 return True
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100365 while time.time() < deadline:
Klement Sekera9225dee2016-12-12 08:36:58 +0100366 if os.path.isfile(self.out_path):
367 break
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700368 self._test.sleep(0) # yield
Klement Sekera9225dee2016-12-12 08:36:58 +0100369 if os.path.isfile(self.out_path):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200370 self.test.logger.debug(
371 "Capture file appeared after %fs" % (time.time() - (deadline - timeout))
372 )
Klement Sekera9225dee2016-12-12 08:36:58 +0100373 else:
374 self.test.logger.debug("Timeout - capture file still nowhere")
Klement Sekeradab231a2016-12-21 08:50:14 +0100375 return False
376 return True
Klement Sekera9225dee2016-12-12 08:36:58 +0100377
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100378 def verify_enough_packet_data_in_pcap(self):
Klement Sekerab91017a2017-02-09 06:04:36 +0100379 """
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100380 Check if enough data is available in file handled by internal pcap
381 reader so that a whole packet can be read.
Klement Sekerab91017a2017-02-09 06:04:36 +0100382
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100383 :returns: True if enough data present, else False
Klement Sekerab91017a2017-02-09 06:04:36 +0100384 """
385 orig_pos = self._pcap_reader.f.tell() # save file position
386 enough_data = False
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100387 # read packet header from pcap
388 packet_header_size = 16
389 caplen = None
390 end_pos = None
391 hdr = self._pcap_reader.f.read(packet_header_size)
392 if len(hdr) == packet_header_size:
393 # parse the capture length - caplen
Klement Sekerab91017a2017-02-09 06:04:36 +0100394 sec, usec, caplen, wirelen = struct.unpack(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200395 self._pcap_reader.endian + "IIII", hdr
396 )
Klement Sekerab91017a2017-02-09 06:04:36 +0100397 self._pcap_reader.f.seek(0, 2) # seek to end of file
398 end_pos = self._pcap_reader.f.tell() # get position at end
399 if end_pos >= orig_pos + len(hdr) + caplen:
400 enough_data = True # yay, we have enough data
Klement Sekerab91017a2017-02-09 06:04:36 +0100401 self._pcap_reader.f.seek(orig_pos, 0) # restore original position
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100402 return enough_data
Klement Sekerab91017a2017-02-09 06:04:36 +0100403
Klement Sekeradab231a2016-12-21 08:50:14 +0100404 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200405 """
406 Wait for next packet captured with a timeout
407
408 :param timeout: How long to wait for the packet
409
410 :returns: Captured packet if no packet arrived within timeout
411 :raises Exception: if no packet arrives within timeout
412 """
Klement Sekeradab231a2016-12-21 08:50:14 +0100413 deadline = time.time() + timeout
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200414 if self._pcap_reader is None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100415 if not self.wait_for_capture_file(timeout):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200416 raise CaptureTimeoutError(
417 "Capture file %s did not appear within timeout" % self.out_path
418 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100419 while time.time() < deadline:
420 try:
421 self._pcap_reader = PcapReader(self.out_path)
422 break
423 except:
Klement Sekerada505f62017-01-04 12:58:53 +0100424 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200425 "Exception in scapy.PcapReader(%s): %s"
426 % (self.out_path, format_exc())
427 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100428 if not self._pcap_reader:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200429 raise CaptureTimeoutError(
430 "Capture file %s did not appear within timeout" % self.out_path
431 )
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200432
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100433 poll = False
434 if timeout > 0:
435 self.test.logger.debug("Waiting for packet")
436 else:
437 poll = True
438 self.test.logger.debug("Polling for packet")
439 while time.time() < deadline or poll:
440 if not self.verify_enough_packet_data_in_pcap():
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700441 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100442 poll = False
443 continue
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200444 p = self._pcap_reader.recv()
445 if p is not None:
Klement Sekeradab231a2016-12-21 08:50:14 +0100446 if filter_out_fn is not None and filter_out_fn(p):
447 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200448 "Packet received after %ss was filtered out"
449 % (time.time() - (deadline - timeout))
450 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100451 else:
Klement Sekerada505f62017-01-04 12:58:53 +0100452 self.test.logger.debug(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200453 "Packet received after %fs"
454 % (time.time() - (deadline - timeout))
455 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100456 return p
Paul Vinciguerra0f6602c2019-03-10 09:10:54 -0700457 self._test.sleep(0) # yield
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100458 poll = False
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200459 self.test.logger.debug("Timeout - no packets received")
Klement Sekeraacb9b8e2017-02-14 02:55:31 +0100460 raise CaptureTimeoutError("Packet didn't arrive within timeout")
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200461
Matej Klotton0178d522016-11-04 11:11:44 +0100462 def create_arp_req(self):
463 """Create ARP request applicable for this interface"""
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200464 return Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) / ARP(
465 op=ARP.who_has,
466 pdst=self.local_ip4,
467 psrc=self.remote_ip4,
468 hwsrc=self.remote_mac,
469 )
Matej Klotton0178d522016-11-04 11:11:44 +0100470
Benoît Ganne2699fe22021-01-18 19:25:38 +0100471 def create_ndp_req(self, addr=None):
Matej Klotton0178d522016-11-04 11:11:44 +0100472 """Create NDP - NS applicable for this interface"""
Benoît Ganne2699fe22021-01-18 19:25:38 +0100473 if not addr:
474 addr = self.local_ip6
475 nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr))
Neale Ranns465a1a32017-01-07 10:04:09 -0800476 d = inet_ntop(socket.AF_INET6, nsma)
477
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200478 return (
479 Ether(dst=in6_getnsmac(nsma))
480 / IPv6(dst=d, src=self.remote_ip6)
481 / ICMPv6ND_NS(tgt=addr)
482 / ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac)
483 )
Matej Klotton0178d522016-11-04 11:11:44 +0100484
485 def resolve_arp(self, pg_interface=None):
486 """Resolve ARP using provided packet-generator interface
487
488 :param pg_interface: interface used to resolve, if None then this
489 interface is used
490
491 """
492 if pg_interface is None:
493 pg_interface = self
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200494 self.test.logger.info(
495 "Sending ARP request for %s on port %s"
496 % (self.local_ip4, pg_interface.name)
497 )
Matej Klotton0178d522016-11-04 11:11:44 +0100498 arp_req = self.create_arp_req()
499 pg_interface.add_stream(arp_req)
500 pg_interface.enable_capture()
501 self.test.pg_start()
Klement Sekera7bb873a2016-11-18 07:38:42 +0100502 self.test.logger.info(self.test.vapi.cli("show trace"))
Klement Sekera9225dee2016-12-12 08:36:58 +0100503 try:
Klement Sekeradab231a2016-12-21 08:50:14 +0100504 captured_packet = pg_interface.wait_for_packet(1)
Klement Sekera9225dee2016-12-12 08:36:58 +0100505 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200506 self.test.logger.info("No ARP received on port %s" % pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100507 return
Klement Sekeradab231a2016-12-21 08:50:14 +0100508 arp_reply = captured_packet.copy() # keep original for exception
Matej Klotton0178d522016-11-04 11:11:44 +0100509 try:
510 if arp_reply[ARP].op == ARP.is_at:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200511 self.test.logger.info(
512 "VPP %s MAC address is %s " % (self.name, arp_reply[ARP].hwsrc)
513 )
Matej Klotton0178d522016-11-04 11:11:44 +0100514 self._local_mac = arp_reply[ARP].hwsrc
515 else:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200516 self.test.logger.info("No ARP received on port %s" % pg_interface.name)
Matej Klotton0178d522016-11-04 11:11:44 +0100517 except:
Klement Sekera7bb873a2016-11-18 07:38:42 +0100518 self.test.logger.error(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200519 ppp("Unexpected response to ARP request:", captured_packet)
520 )
Matej Klotton0178d522016-11-04 11:11:44 +0100521 raise
522
Benoît Ganne2699fe22021-01-18 19:25:38 +0100523 def resolve_ndp(self, pg_interface=None, timeout=1, link_layer=False):
Matej Klotton0178d522016-11-04 11:11:44 +0100524 """Resolve NDP using provided packet-generator interface
525
526 :param pg_interface: interface used to resolve, if None then this
527 interface is used
Klement Sekeradab231a2016-12-21 08:50:14 +0100528 :param timeout: how long to wait for response before giving up
Benoît Ganne2699fe22021-01-18 19:25:38 +0100529 :param link_layer: resolve for global address if False (default)
530 or for link-layer address if True
Matej Klotton0178d522016-11-04 11:11:44 +0100531
532 """
533 if pg_interface is None:
534 pg_interface = self
Benoît Ganne2699fe22021-01-18 19:25:38 +0100535 addr = self.local_ip6_ll if link_layer else self.local_ip6
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200536 self.test.logger.info(
537 "Sending NDP request for %s on port %s" % (addr, pg_interface.name)
538 )
Benoît Ganne2699fe22021-01-18 19:25:38 +0100539 ndp_req = self.create_ndp_req(addr)
Matej Klotton0178d522016-11-04 11:11:44 +0100540 pg_interface.add_stream(ndp_req)
541 pg_interface.enable_capture()
542 self.test.pg_start()
Klement Sekeradab231a2016-12-21 08:50:14 +0100543 now = time.time()
544 deadline = now + timeout
Neale Ranns82a06a92016-12-08 20:05:33 +0000545 # Enabling IPv6 on an interface can generate more than the
546 # ND reply we are looking for (namely MLD). So loop through
547 # the replies to look for want we want.
Klement Sekeradab231a2016-12-21 08:50:14 +0100548 while now < deadline:
549 try:
550 captured_packet = pg_interface.wait_for_packet(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200551 deadline - now, filter_out_fn=None
552 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100553 except:
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200554 self.test.logger.error("Timeout while waiting for NDP response")
Klement Sekeradab231a2016-12-21 08:50:14 +0100555 raise
556 ndp_reply = captured_packet.copy() # keep original for exception
Neale Ranns82a06a92016-12-08 20:05:33 +0000557 try:
558 ndp_na = ndp_reply[ICMPv6ND_NA]
559 opt = ndp_na[ICMPv6NDOptDstLLAddr]
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200560 self.test.logger.info(
561 "VPP %s MAC address is %s " % (self.name, opt.lladdr)
562 )
Neale Ranns82a06a92016-12-08 20:05:33 +0000563 self._local_mac = opt.lladdr
Klement Sekeradab231a2016-12-21 08:50:14 +0100564 self.test.logger.debug(self.test.vapi.cli("show trace"))
565 # we now have the MAC we've been after
566 return
Neale Ranns82a06a92016-12-08 20:05:33 +0000567 except:
568 self.test.logger.info(
Klement Sekerad9b0c6f2022-04-26 19:02:15 +0200569 ppp("Unexpected response to NDP request:", captured_packet)
570 )
Klement Sekeradab231a2016-12-21 08:50:14 +0100571 now = time.time()
572
573 self.test.logger.debug(self.test.vapi.cli("show trace"))
574 raise Exception("Timeout while waiting for NDP response")