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"""
50 """pcap file path - captured packets"""
55 """ pcap file path - injected packets"""
59 def capture_cli(self):
60 """CLI string to start capture on this interface"""
61 return self._capture_cli
65 """capture name for this interface"""
70 """CLI string to load the injected packets"""
71 return self._input_cli
74 def in_history_counter(self):
75 """Self-incrementing counter used when renaming old pcap files"""
76 v = self._in_history_counter
77 self._in_history_counter += 1
81 def out_history_counter(self):
82 """Self-incrementing counter used when renaming old pcap files"""
83 v = self._out_history_counter
84 self._out_history_counter += 1
87 def __init__(self, test, pg_index):
88 """ Create VPP packet-generator interface """
89 super(VppPGInterface, self).__init__(test)
91 r = test.vapi.pg_create_interface(pg_index)
92 self.set_sw_if_index(r.sw_if_index)
94 self._in_history_counter = 0
95 self._out_history_counter = 0
96 self._out_assert_counter = 0
97 self._pg_index = pg_index
98 self._out_file = "pg%u_out.pcap" % self.pg_index
99 self._out_path = self.test.tempdir + "/" + self._out_file
100 self._in_file = "pg%u_in.pcap" % self.pg_index
101 self._in_path = self.test.tempdir + "/" + self._in_file
102 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
103 self.pg_index, self.out_path)
104 self._cap_name = "pcap%u" % self.sw_if_index
106 "packet-generator new pcap %s source pg%u name %s" % (
107 self.in_path, self.pg_index, self.cap_name)
109 def enable_capture(self):
110 """ Enable capture on this packet-generator interface"""
112 if os.path.isfile(self.out_path):
113 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
117 self.out_history_counter,
119 self.test.logger.debug("Renaming %s->%s" %
120 (self.out_path, name))
121 os.rename(self.out_path, name)
124 # FIXME this should be an API, but no such exists atm
125 self.test.vapi.cli(self.capture_cli)
126 self._pcap_reader = None
128 def add_stream(self, pkts):
130 Add a stream of packets to this packet-generator
132 :param pkts: iterable packets
136 if os.path.isfile(self.in_path):
137 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %\
141 self.in_history_counter,
143 self.test.logger.debug("Renaming %s->%s" %
144 (self.in_path, name))
145 os.rename(self.in_path, name)
148 wrpcap(self.in_path, pkts)
149 self.test.register_capture(self.cap_name)
150 # FIXME this should be an API, but no such exists atm
151 self.test.vapi.cli(self.input_cli)
153 def generate_debug_aid(self, kind):
154 """ Create a hardlink to the out file with a counter and a file
155 containing stack trace to ease debugging in case of multiple capture
157 self.test.logger.debug("Generating debug aid for %s on %s" %
159 link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
160 (self.test.tempdir, self._name,
161 self._out_assert_counter, kind, suffix)
162 for suffix in ["pcap", "stack"]
164 os.link(self.out_path, link_path)
165 with open(stack_path, "w") as f:
166 f.writelines(format_stack())
167 self._out_assert_counter += 1
169 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
170 """ Helper method to get capture and filter it """
172 if not self.wait_for_capture_file(timeout):
174 output = rdpcap(self.out_path)
175 self.test.logger.debug("Capture has %s packets" % len(output.res))
177 self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
178 (self.out_path, format_exc()))
180 before = len(output.res)
182 output.res = [p for p in output.res if not filter_out_fn(p)]
183 removed = before - len(output.res)
185 self.test.logger.debug(
186 "Filtered out %s packets from capture (returning %s)" %
187 (removed, len(output.res)))
190 def get_capture(self, expected_count=None, remark=None, timeout=1,
191 filter_out_fn=is_ipv6_misc):
192 """ Get captured packets
194 :param expected_count: expected number of packets to capture, if None,
195 then self.test.packet_count_for_dst_pg_idx is
196 used to lookup the expected count
197 :param remark: remark printed into debug logs
198 :param timeout: how long to wait for packets
199 :param filter_out_fn: filter applied to each packet, packets for which
200 the filter returns True are removed from capture
201 :returns: iterable packets
203 remaining_time = timeout
205 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
206 based_on = "based on provided argument"
207 if expected_count is None:
209 self.test.get_packet_count_for_if_idx(self.sw_if_index)
210 based_on = "based on stored packet_infos"
211 if expected_count == 0:
213 "Internal error, expected packet count for %s is 0!" %
215 self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
216 expected_count, based_on, name))
217 while remaining_time > 0:
219 capture = self._get_capture(remaining_time, filter_out_fn)
220 elapsed_time = time.time() - before
222 if len(capture.res) == expected_count:
223 # bingo, got the packets we expected
225 elif len(capture.res) > expected_count:
226 self.test.logger.error(
227 ppc("Unexpected packets captured:", capture))
230 self.test.logger.debug("Partial capture containing %s "
231 "packets doesn't match expected "
233 (len(capture.res), expected_count))
234 elif expected_count == 0:
235 # bingo, got None as we expected - return empty capture
237 remaining_time -= elapsed_time
239 self.generate_debug_aid("count-mismatch")
240 raise Exception("Captured packets mismatch, captured %s packets, "
241 "expected %s packets on %s" %
242 (len(capture.res), expected_count, name))
244 raise Exception("No packets captured on %s" % name)
246 def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
247 """ Assert that nothing unfiltered was captured on interface
249 :param remark: remark printed into debug logs
250 :param filter_out_fn: filter applied to each packet, packets for which
251 the filter returns True are removed from capture
253 if os.path.isfile(self.out_path):
255 capture = self.get_capture(
256 0, remark=remark, filter_out_fn=filter_out_fn)
257 if not capture or len(capture.res) == 0:
258 # junk filtered out, we're good
262 self.generate_debug_aid("empty-assert")
264 raise AssertionError(
265 "Non-empty capture file present for interface %s (%s)" %
268 raise AssertionError("Capture file present for interface %s" %
271 def wait_for_capture_file(self, timeout=1):
273 Wait until pcap capture file appears
275 :param timeout: How long to wait for the packet (default 1s)
277 :returns: True/False if the file is present or appears within timeout
279 deadline = time.time() + timeout
280 if not os.path.isfile(self.out_path):
281 self.test.logger.debug("Waiting for capture file %s to appear, "
282 "timeout is %ss" % (self.out_path, timeout))
284 self.test.logger.debug("Capture file %s already exists" %
287 while time.time() < deadline:
288 if os.path.isfile(self.out_path):
290 self._test.sleep(0) # yield
291 if os.path.isfile(self.out_path):
292 self.test.logger.debug("Capture file appeared after %fs" %
293 (time.time() - (deadline - timeout)))
295 self.test.logger.debug("Timeout - capture file still nowhere")
299 def verify_enough_packet_data_in_pcap(self):
301 Check if enough data is available in file handled by internal pcap
302 reader so that a whole packet can be read.
304 :returns: True if enough data present, else False
306 orig_pos = self._pcap_reader.f.tell() # save file position
308 # read packet header from pcap
309 packet_header_size = 16
312 hdr = self._pcap_reader.f.read(packet_header_size)
313 if len(hdr) == packet_header_size:
314 # parse the capture length - caplen
315 sec, usec, caplen, wirelen = struct.unpack(
316 self._pcap_reader.endian + "IIII", hdr)
317 self._pcap_reader.f.seek(0, 2) # seek to end of file
318 end_pos = self._pcap_reader.f.tell() # get position at end
319 if end_pos >= orig_pos + len(hdr) + caplen:
320 enough_data = True # yay, we have enough data
321 self._pcap_reader.f.seek(orig_pos, 0) # restore original position
324 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
326 Wait for next packet captured with a timeout
328 :param timeout: How long to wait for the packet
330 :returns: Captured packet if no packet arrived within timeout
331 :raises Exception: if no packet arrives within timeout
333 deadline = time.time() + timeout
334 if self._pcap_reader is None:
335 if not self.wait_for_capture_file(timeout):
336 raise CaptureTimeoutError("Capture file %s did not appear "
337 "within timeout" % self.out_path)
338 while time.time() < deadline:
340 self._pcap_reader = PcapReader(self.out_path)
343 self.test.logger.debug(
344 "Exception in scapy.PcapReader(%s): %s" %
345 (self.out_path, format_exc()))
346 if not self._pcap_reader:
347 raise CaptureTimeoutError("Capture file %s did not appear within "
348 "timeout" % self.out_path)
352 self.test.logger.debug("Waiting for packet")
355 self.test.logger.debug("Polling for packet")
356 while time.time() < deadline or poll:
357 if not self.verify_enough_packet_data_in_pcap():
358 self._test.sleep(0) # yield
361 p = self._pcap_reader.recv()
363 if filter_out_fn is not None and filter_out_fn(p):
364 self.test.logger.debug(
365 "Packet received after %ss was filtered out" %
366 (time.time() - (deadline - timeout)))
368 self.test.logger.debug(
369 "Packet received after %fs" %
370 (time.time() - (deadline - timeout)))
372 self._test.sleep(0) # yield
374 self.test.logger.debug("Timeout - no packets received")
375 raise CaptureTimeoutError("Packet didn't arrive within timeout")
377 def create_arp_req(self):
378 """Create ARP request applicable for this interface"""
379 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
380 ARP(op=ARP.who_has, pdst=self.local_ip4,
381 psrc=self.remote_ip4, hwsrc=self.remote_mac))
383 def create_ndp_req(self):
384 """Create NDP - NS applicable for this interface"""
385 nsma = in6_getnsma(inet_pton(socket.AF_INET6, self.local_ip6))
386 d = inet_ntop(socket.AF_INET6, nsma)
388 return (Ether(dst=in6_getnsmac(nsma)) /
389 IPv6(dst=d, src=self.remote_ip6) /
390 ICMPv6ND_NS(tgt=self.local_ip6) /
391 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
393 def resolve_arp(self, pg_interface=None):
394 """Resolve ARP using provided packet-generator interface
396 :param pg_interface: interface used to resolve, if None then this
400 if pg_interface is None:
402 self.test.logger.info("Sending ARP request for %s on port %s" %
403 (self.local_ip4, pg_interface.name))
404 arp_req = self.create_arp_req()
405 pg_interface.add_stream(arp_req)
406 pg_interface.enable_capture()
408 self.test.logger.info(self.test.vapi.cli("show trace"))
410 captured_packet = pg_interface.wait_for_packet(1)
412 self.test.logger.info("No ARP received on port %s" %
415 arp_reply = captured_packet.copy() # keep original for exception
416 # Make Dot1AD packet content recognizable to scapy
417 if arp_reply.type == 0x88a8:
418 arp_reply.type = 0x8100
419 arp_reply = Ether(scapy.compat.raw(arp_reply))
421 if arp_reply[ARP].op == ARP.is_at:
422 self.test.logger.info("VPP %s MAC address is %s " %
423 (self.name, arp_reply[ARP].hwsrc))
424 self._local_mac = arp_reply[ARP].hwsrc
426 self.test.logger.info("No ARP received on port %s" %
429 self.test.logger.error(
430 ppp("Unexpected response to ARP request:", captured_packet))
433 def resolve_ndp(self, pg_interface=None, timeout=1):
434 """Resolve NDP using provided packet-generator interface
436 :param pg_interface: interface used to resolve, if None then this
438 :param timeout: how long to wait for response before giving up
441 if pg_interface is None:
443 self.test.logger.info("Sending NDP request for %s on port %s" %
444 (self.local_ip6, pg_interface.name))
445 ndp_req = self.create_ndp_req()
446 pg_interface.add_stream(ndp_req)
447 pg_interface.enable_capture()
450 deadline = now + timeout
451 # Enabling IPv6 on an interface can generate more than the
452 # ND reply we are looking for (namely MLD). So loop through
453 # the replies to look for want we want.
454 while now < deadline:
456 captured_packet = pg_interface.wait_for_packet(
457 deadline - now, filter_out_fn=None)
459 self.test.logger.error(
460 "Timeout while waiting for NDP response")
462 ndp_reply = captured_packet.copy() # keep original for exception
463 # Make Dot1AD packet content recognizable to scapy
464 if ndp_reply.type == 0x88a8:
465 self._test.logger.info(
466 "Replacing EtherType: 0x88a8 with "
467 "0x8100 and regenerating Ethernet header. ")
468 ndp_reply.type = 0x8100
469 ndp_reply = Ether(scapy.compat.raw(ndp_reply))
471 ndp_na = ndp_reply[ICMPv6ND_NA]
472 opt = ndp_na[ICMPv6NDOptDstLLAddr]
473 self.test.logger.info("VPP %s MAC address is %s " %
474 (self.name, opt.lladdr))
475 self._local_mac = opt.lladdr
476 self.test.logger.debug(self.test.vapi.cli("show trace"))
477 # we now have the MAC we've been after
480 self.test.logger.info(
481 ppp("Unexpected response to NDP request:",
485 self.test.logger.debug(self.test.vapi.cli("show trace"))
486 raise Exception("Timeout while waiting for NDP response")