5 from traceback import format_exc, format_stack
8 from scapy.utils import wrpcap, rdpcap, PcapReader
9 from scapy.plist import PacketList
10 from vpp_interface import VppInterface
12 from scapy.layers.l2 import Ether, ARP
13 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
14 ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
16 from util import ppp, ppc
17 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
18 from scapy.utils import inet_pton, inet_ntop
21 class CaptureTimeoutError(Exception):
22 """ Exception raised if capture or packet doesn't appear within timeout """
27 """ Is packet one of uninteresting IPv6 broadcasts? """
28 if p.haslayer(ICMPv6ND_RA):
29 if in6_ismaddr(p[IPv6].dst):
31 if p.haslayer(IPv6ExtHdrHopByHop):
32 for o in p[IPv6ExtHdrHopByHop].options:
33 if isinstance(o, RouterAlert):
38 class VppPGInterface(VppInterface):
40 VPP packet-generator interface
45 """packet-generator interface index assigned by VPP"""
49 def gso_enabled(self):
50 """gso enabled on packet-generator interface"""
51 if self._gso_enabled == 0:
57 """gso size on packet-generator interface"""
62 """pcap file path - captured packets"""
67 """ pcap file path - injected packets"""
71 def capture_cli(self):
72 """CLI string to start capture on this interface"""
73 return self._capture_cli
77 """capture name for this interface"""
82 """CLI string to load the injected packets"""
83 if self._nb_replays is not None:
84 return "%s limit %d" % (self._input_cli, self._nb_replays)
85 if self._worker is not None:
86 return "%s worker %d" % (self._input_cli, self._worker)
87 return self._input_cli
90 def in_history_counter(self):
91 """Self-incrementing counter used when renaming old pcap files"""
92 v = self._in_history_counter
93 self._in_history_counter += 1
97 def out_history_counter(self):
98 """Self-incrementing counter used when renaming old pcap files"""
99 v = self._out_history_counter
100 self._out_history_counter += 1
103 def __init__(self, test, pg_index, gso, gso_size):
104 """ Create VPP packet-generator interface """
105 super(VppPGInterface, self).__init__(test)
107 r = test.vapi.pg_create_interface(pg_index, gso, gso_size)
108 self.set_sw_if_index(r.sw_if_index)
110 self._in_history_counter = 0
111 self._out_history_counter = 0
112 self._out_assert_counter = 0
113 self._pg_index = pg_index
114 self._gso_enabled = gso
115 self._gso_size = gso_size
116 self._out_file = "pg%u_out.pcap" % self.pg_index
117 self._out_path = self.test.tempdir + "/" + self._out_file
118 self._in_file = "pg%u_in.pcap" % self.pg_index
119 self._in_path = self.test.tempdir + "/" + self._in_file
120 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
121 self.pg_index, self.out_path)
122 self._cap_name = "pcap%u-sw_if_index-%s" % (
123 self.pg_index, self.sw_if_index)
125 "packet-generator new pcap %s source pg%u name %s" % (
126 self.in_path, self.pg_index, self.cap_name)
127 self._nb_replays = None
129 def _rename_previous_capture_file(self, path, counter, file):
130 # if a file from a previous capture exists, rename it.
132 if os.path.isfile(path):
133 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
139 self.test.logger.debug("Renaming %s->%s" %
141 os.rename(path, name)
143 self.test.logger.debug("OSError: Could not rename %s %s" %
146 def enable_capture(self):
147 """ Enable capture on this packet-generator interface
148 of at most n packets.
149 If n < 0, this is no limit
151 # disable the capture to flush the capture
152 self.disable_capture()
153 self._rename_previous_capture_file(self.out_path,
154 self.out_history_counter,
156 # FIXME this should be an API, but no such exists atm
157 self.test.vapi.cli(self.capture_cli)
158 self._pcap_reader = None
160 def disable_capture(self):
161 self.test.vapi.cli("%s disable" % self.capture_cli)
163 def add_stream(self, pkts, nb_replays=None, worker=None):
165 Add a stream of packets to this packet-generator
167 :param pkts: iterable packets
170 self._worker = worker
171 self._nb_replays = nb_replays
172 self._rename_previous_capture_file(self.in_path,
173 self.in_history_counter,
175 wrpcap(self.in_path, pkts)
176 self.test.register_capture(self.cap_name)
177 # FIXME this should be an API, but no such exists atm
178 self.test.vapi.cli(self.input_cli)
180 def generate_debug_aid(self, kind):
181 """ Create a hardlink to the out file with a counter and a file
182 containing stack trace to ease debugging in case of multiple capture
184 self.test.logger.debug("Generating debug aid for %s on %s" %
186 link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
187 (self.test.tempdir, self._name,
188 self._out_assert_counter, kind, suffix)
189 for suffix in ["pcap", "stack"]
191 os.link(self.out_path, link_path)
192 with open(stack_path, "w") as f:
193 f.writelines(format_stack())
194 self._out_assert_counter += 1
196 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
197 """ Helper method to get capture and filter it """
199 if not self.wait_for_capture_file(timeout):
201 output = rdpcap(self.out_path)
202 self.test.logger.debug("Capture has %s packets" % len(output.res))
204 self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
205 (self.out_path, format_exc()))
207 before = len(output.res)
209 output.res = [p for p in output.res if not filter_out_fn(p)]
210 removed = before - len(output.res)
212 self.test.logger.debug(
213 "Filtered out %s packets from capture (returning %s)" %
214 (removed, len(output.res)))
217 def get_capture(self, expected_count=None, remark=None, timeout=1,
218 filter_out_fn=is_ipv6_misc):
219 """ Get captured packets
221 :param expected_count: expected number of packets to capture, if None,
222 then self.test.packet_count_for_dst_pg_idx is
223 used to lookup the expected count
224 :param remark: remark printed into debug logs
225 :param timeout: how long to wait for packets
226 :param filter_out_fn: filter applied to each packet, packets for which
227 the filter returns True are removed from capture
228 :returns: iterable packets
230 remaining_time = timeout
232 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
233 based_on = "based on provided argument"
234 if expected_count is None:
236 self.test.get_packet_count_for_if_idx(self.sw_if_index)
237 based_on = "based on stored packet_infos"
238 if expected_count == 0:
240 "Internal error, expected packet count for %s is 0!" %
242 self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
243 expected_count, based_on, name))
244 while remaining_time > 0:
246 capture = self._get_capture(remaining_time, filter_out_fn)
247 elapsed_time = time.time() - before
249 if len(capture.res) == expected_count:
250 # bingo, got the packets we expected
252 elif len(capture.res) > expected_count:
253 self.test.logger.error(
254 ppc("Unexpected packets captured:", capture))
257 self.test.logger.debug("Partial capture containing %s "
258 "packets doesn't match expected "
260 (len(capture.res), expected_count))
261 elif expected_count == 0:
262 # bingo, got None as we expected - return empty capture
264 remaining_time -= elapsed_time
266 self.generate_debug_aid("count-mismatch")
267 raise Exception("Captured packets mismatch, captured %s packets, "
268 "expected %s packets on %s" %
269 (len(capture.res), expected_count, name))
271 raise Exception("No packets captured on %s" % name)
273 def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
274 """ Assert that nothing unfiltered was captured on interface
276 :param remark: remark printed into debug logs
277 :param filter_out_fn: filter applied to each packet, packets for which
278 the filter returns True are removed from capture
280 if os.path.isfile(self.out_path):
282 capture = self.get_capture(
283 0, remark=remark, filter_out_fn=filter_out_fn)
284 if not capture or len(capture.res) == 0:
285 # junk filtered out, we're good
289 self.generate_debug_aid("empty-assert")
291 raise AssertionError(
292 "Non-empty capture file present for interface %s (%s)" %
295 raise AssertionError("Capture file present for interface %s" %
298 def wait_for_capture_file(self, timeout=1):
300 Wait until pcap capture file appears
302 :param timeout: How long to wait for the packet (default 1s)
304 :returns: True/False if the file is present or appears within timeout
306 deadline = time.time() + timeout
307 if not os.path.isfile(self.out_path):
308 self.test.logger.debug("Waiting for capture file %s to appear, "
309 "timeout is %ss" % (self.out_path, timeout))
311 self.test.logger.debug("Capture file %s already exists" %
314 while time.time() < deadline:
315 if os.path.isfile(self.out_path):
317 self._test.sleep(0) # yield
318 if os.path.isfile(self.out_path):
319 self.test.logger.debug("Capture file appeared after %fs" %
320 (time.time() - (deadline - timeout)))
322 self.test.logger.debug("Timeout - capture file still nowhere")
326 def verify_enough_packet_data_in_pcap(self):
328 Check if enough data is available in file handled by internal pcap
329 reader so that a whole packet can be read.
331 :returns: True if enough data present, else False
333 orig_pos = self._pcap_reader.f.tell() # save file position
335 # read packet header from pcap
336 packet_header_size = 16
339 hdr = self._pcap_reader.f.read(packet_header_size)
340 if len(hdr) == packet_header_size:
341 # parse the capture length - caplen
342 sec, usec, caplen, wirelen = struct.unpack(
343 self._pcap_reader.endian + "IIII", hdr)
344 self._pcap_reader.f.seek(0, 2) # seek to end of file
345 end_pos = self._pcap_reader.f.tell() # get position at end
346 if end_pos >= orig_pos + len(hdr) + caplen:
347 enough_data = True # yay, we have enough data
348 self._pcap_reader.f.seek(orig_pos, 0) # restore original position
351 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
353 Wait for next packet captured with a timeout
355 :param timeout: How long to wait for the packet
357 :returns: Captured packet if no packet arrived within timeout
358 :raises Exception: if no packet arrives within timeout
360 deadline = time.time() + timeout
361 if self._pcap_reader is None:
362 if not self.wait_for_capture_file(timeout):
363 raise CaptureTimeoutError("Capture file %s did not appear "
364 "within timeout" % self.out_path)
365 while time.time() < deadline:
367 self._pcap_reader = PcapReader(self.out_path)
370 self.test.logger.debug(
371 "Exception in scapy.PcapReader(%s): %s" %
372 (self.out_path, format_exc()))
373 if not self._pcap_reader:
374 raise CaptureTimeoutError("Capture file %s did not appear within "
375 "timeout" % self.out_path)
379 self.test.logger.debug("Waiting for packet")
382 self.test.logger.debug("Polling for packet")
383 while time.time() < deadline or poll:
384 if not self.verify_enough_packet_data_in_pcap():
385 self._test.sleep(0) # yield
388 p = self._pcap_reader.recv()
390 if filter_out_fn is not None and filter_out_fn(p):
391 self.test.logger.debug(
392 "Packet received after %ss was filtered out" %
393 (time.time() - (deadline - timeout)))
395 self.test.logger.debug(
396 "Packet received after %fs" %
397 (time.time() - (deadline - timeout)))
399 self._test.sleep(0) # yield
401 self.test.logger.debug("Timeout - no packets received")
402 raise CaptureTimeoutError("Packet didn't arrive within timeout")
404 def create_arp_req(self):
405 """Create ARP request applicable for this interface"""
406 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
407 ARP(op=ARP.who_has, pdst=self.local_ip4,
408 psrc=self.remote_ip4, hwsrc=self.remote_mac))
410 def create_ndp_req(self):
411 """Create NDP - NS applicable for this interface"""
412 nsma = in6_getnsma(inet_pton(socket.AF_INET6, self.local_ip6))
413 d = inet_ntop(socket.AF_INET6, nsma)
415 return (Ether(dst=in6_getnsmac(nsma)) /
416 IPv6(dst=d, src=self.remote_ip6) /
417 ICMPv6ND_NS(tgt=self.local_ip6) /
418 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
420 def resolve_arp(self, pg_interface=None):
421 """Resolve ARP using provided packet-generator interface
423 :param pg_interface: interface used to resolve, if None then this
427 if pg_interface is None:
429 self.test.logger.info("Sending ARP request for %s on port %s" %
430 (self.local_ip4, pg_interface.name))
431 arp_req = self.create_arp_req()
432 pg_interface.add_stream(arp_req)
433 pg_interface.enable_capture()
435 self.test.logger.info(self.test.vapi.cli("show trace"))
437 captured_packet = pg_interface.wait_for_packet(1)
439 self.test.logger.info("No ARP received on port %s" %
442 arp_reply = captured_packet.copy() # keep original for exception
444 if arp_reply[ARP].op == ARP.is_at:
445 self.test.logger.info("VPP %s MAC address is %s " %
446 (self.name, arp_reply[ARP].hwsrc))
447 self._local_mac = arp_reply[ARP].hwsrc
449 self.test.logger.info("No ARP received on port %s" %
452 self.test.logger.error(
453 ppp("Unexpected response to ARP request:", captured_packet))
456 def resolve_ndp(self, pg_interface=None, timeout=1):
457 """Resolve NDP using provided packet-generator interface
459 :param pg_interface: interface used to resolve, if None then this
461 :param timeout: how long to wait for response before giving up
464 if pg_interface is None:
466 self.test.logger.info("Sending NDP request for %s on port %s" %
467 (self.local_ip6, pg_interface.name))
468 ndp_req = self.create_ndp_req()
469 pg_interface.add_stream(ndp_req)
470 pg_interface.enable_capture()
473 deadline = now + timeout
474 # Enabling IPv6 on an interface can generate more than the
475 # ND reply we are looking for (namely MLD). So loop through
476 # the replies to look for want we want.
477 while now < deadline:
479 captured_packet = pg_interface.wait_for_packet(
480 deadline - now, filter_out_fn=None)
482 self.test.logger.error(
483 "Timeout while waiting for NDP response")
485 ndp_reply = captured_packet.copy() # keep original for exception
487 ndp_na = ndp_reply[ICMPv6ND_NA]
488 opt = ndp_na[ICMPv6NDOptDstLLAddr]
489 self.test.logger.info("VPP %s MAC address is %s " %
490 (self.name, opt.lladdr))
491 self._local_mac = opt.lladdr
492 self.test.logger.debug(self.test.vapi.cli("show trace"))
493 # we now have the MAC we've been after
496 self.test.logger.info(
497 ppp("Unexpected response to NDP request:",
501 self.test.logger.debug(self.test.vapi.cli("show trace"))
502 raise Exception("Timeout while waiting for NDP response")