5 from traceback import format_exc, format_stack
6 from scapy.utils import wrpcap, rdpcap, PcapReader
7 from scapy.plist import PacketList
8 from vpp_interface import VppInterface
10 from scapy.layers.l2 import Ether, ARP
11 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
12 ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
14 from util import ppp, ppc
15 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
16 from scapy.utils import inet_pton, inet_ntop
19 class CaptureTimeoutError(Exception):
20 """ Exception raised if capture or packet doesn't appear within timeout """
25 """ Is packet one of uninteresting IPv6 broadcasts? """
26 if p.haslayer(ICMPv6ND_RA):
27 if in6_ismaddr(p[IPv6].dst):
29 if p.haslayer(IPv6ExtHdrHopByHop):
30 for o in p[IPv6ExtHdrHopByHop].options:
31 if isinstance(o, RouterAlert):
36 class VppPGInterface(VppInterface):
38 VPP packet-generator interface
43 """packet-generator interface index assigned by VPP"""
48 """pcap file path - captured packets"""
53 """ pcap file path - injected packets"""
57 def capture_cli(self):
58 """CLI string to start capture on this interface"""
59 return self._capture_cli
63 """capture name for this interface"""
68 """CLI string to load the injected packets"""
69 return self._input_cli
72 def in_history_counter(self):
73 """Self-incrementing counter used when renaming old pcap files"""
74 v = self._in_history_counter
75 self._in_history_counter += 1
79 def out_history_counter(self):
80 """Self-incrementing counter used when renaming old pcap files"""
81 v = self._out_history_counter
82 self._out_history_counter += 1
85 def __init__(self, test, pg_index):
86 """ Create VPP packet-generator interface """
87 r = test.vapi.pg_create_interface(pg_index)
88 self._sw_if_index = r.sw_if_index
90 super(VppPGInterface, self).__init__(test)
92 self._in_history_counter = 0
93 self._out_history_counter = 0
94 self._out_assert_counter = 0
95 self._pg_index = pg_index
96 self._out_file = "pg%u_out.pcap" % self.pg_index
97 self._out_path = self.test.tempdir + "/" + self._out_file
98 self._in_file = "pg%u_in.pcap" % self.pg_index
99 self._in_path = self.test.tempdir + "/" + self._in_file
100 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
101 self.pg_index, self.out_path)
102 self._cap_name = "pcap%u" % self.sw_if_index
104 "packet-generator new pcap %s source pg%u name %s" % (
105 self.in_path, self.pg_index, self.cap_name)
107 def enable_capture(self):
108 """ Enable capture on this packet-generator interface"""
110 if os.path.isfile(self.out_path):
111 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
115 self.out_history_counter,
117 self.test.logger.debug("Renaming %s->%s" %
118 (self.out_path, name))
119 os.rename(self.out_path, name)
122 # FIXME this should be an API, but no such exists atm
123 self.test.vapi.cli(self.capture_cli)
124 self._pcap_reader = None
126 def add_stream(self, pkts):
128 Add a stream of packets to this packet-generator
130 :param pkts: iterable packets
134 if os.path.isfile(self.in_path):
135 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %\
139 self.in_history_counter,
141 self.test.logger.debug("Renaming %s->%s" %
142 (self.in_path, name))
143 os.rename(self.in_path, name)
146 wrpcap(self.in_path, pkts)
147 self.test.register_capture(self.cap_name)
148 # FIXME this should be an API, but no such exists atm
149 self.test.vapi.cli(self.input_cli)
151 def generate_debug_aid(self, kind):
152 """ Create a hardlink to the out file with a counter and a file
153 containing stack trace to ease debugging in case of multiple capture
155 self.test.logger.debug("Generating debug aid for %s on %s" %
157 link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
158 (self.test.tempdir, self._name,
159 self._out_assert_counter, kind, suffix)
160 for suffix in ["pcap", "stack"]
162 os.link(self.out_path, link_path)
163 with open(stack_path, "w") as f:
164 f.writelines(format_stack())
165 self._out_assert_counter += 1
167 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
168 """ Helper method to get capture and filter it """
170 if not self.wait_for_capture_file(timeout):
172 output = rdpcap(self.out_path)
173 self.test.logger.debug("Capture has %s packets" % len(output.res))
175 self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
176 (self.out_path, format_exc()))
178 before = len(output.res)
180 output.res = [p for p in output.res if not filter_out_fn(p)]
181 removed = before - len(output.res)
183 self.test.logger.debug(
184 "Filtered out %s packets from capture (returning %s)" %
185 (removed, len(output.res)))
188 def get_capture(self, expected_count=None, remark=None, timeout=1,
189 filter_out_fn=is_ipv6_misc):
190 """ Get captured packets
192 :param expected_count: expected number of packets to capture, if None,
193 then self.test.packet_count_for_dst_pg_idx is
194 used to lookup the expected count
195 :param remark: remark printed into debug logs
196 :param timeout: how long to wait for packets
197 :param filter_out_fn: filter applied to each packet, packets for which
198 the filter returns True are removed from capture
199 :returns: iterable packets
201 remaining_time = timeout
203 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
204 based_on = "based on provided argument"
205 if expected_count is None:
207 self.test.get_packet_count_for_if_idx(self.sw_if_index)
208 based_on = "based on stored packet_infos"
209 if expected_count == 0:
211 "Internal error, expected packet count for %s is 0!" %
213 self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
214 expected_count, based_on, name))
215 while remaining_time > 0:
217 capture = self._get_capture(remaining_time, filter_out_fn)
218 elapsed_time = time.time() - before
220 if len(capture.res) == expected_count:
221 # bingo, got the packets we expected
223 elif len(capture.res) > expected_count:
224 self.test.logger.error(
225 ppc("Unexpected packets captured:", capture))
228 self.test.logger.debug("Partial capture containing %s "
229 "packets doesn't match expected "
231 (len(capture.res), expected_count))
232 elif expected_count == 0:
233 # bingo, got None as we expected - return empty capture
235 remaining_time -= elapsed_time
237 self.generate_debug_aid("count-mismatch")
238 raise Exception("Captured packets mismatch, captured %s packets, "
239 "expected %s packets on %s" %
240 (len(capture.res), expected_count, name))
242 raise Exception("No packets captured on %s" % name)
244 def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
245 """ Assert that nothing unfiltered was captured on interface
247 :param remark: remark printed into debug logs
248 :param filter_out_fn: filter applied to each packet, packets for which
249 the filter returns True are removed from capture
251 if os.path.isfile(self.out_path):
253 capture = self.get_capture(
254 0, remark=remark, filter_out_fn=filter_out_fn)
255 if not capture or len(capture.res) == 0:
256 # junk filtered out, we're good
260 self.generate_debug_aid("empty-assert")
262 raise AssertionError(
263 "Non-empty capture file present for interface %s (%s)" %
266 raise AssertionError("Capture file present for interface %s" %
269 def wait_for_capture_file(self, timeout=1):
271 Wait until pcap capture file appears
273 :param timeout: How long to wait for the packet (default 1s)
275 :returns: True/False if the file is present or appears within timeout
277 deadline = time.time() + timeout
278 if not os.path.isfile(self.out_path):
279 self.test.logger.debug("Waiting for capture file %s to appear, "
280 "timeout is %ss" % (self.out_path, timeout))
282 self.test.logger.debug("Capture file %s already exists" %
285 while time.time() < deadline:
286 if os.path.isfile(self.out_path):
288 time.sleep(0) # yield
289 if os.path.isfile(self.out_path):
290 self.test.logger.debug("Capture file appeared after %fs" %
291 (time.time() - (deadline - timeout)))
293 self.test.logger.debug("Timeout - capture file still nowhere")
297 def verify_enough_packet_data_in_pcap(self):
299 Check if enough data is available in file handled by internal pcap
300 reader so that a whole packet can be read.
302 :returns: True if enough data present, else False
304 orig_pos = self._pcap_reader.f.tell() # save file position
306 # read packet header from pcap
307 packet_header_size = 16
310 hdr = self._pcap_reader.f.read(packet_header_size)
311 if len(hdr) == packet_header_size:
312 # parse the capture length - caplen
313 sec, usec, caplen, wirelen = struct.unpack(
314 self._pcap_reader.endian + "IIII", hdr)
315 self._pcap_reader.f.seek(0, 2) # seek to end of file
316 end_pos = self._pcap_reader.f.tell() # get position at end
317 if end_pos >= orig_pos + len(hdr) + caplen:
318 enough_data = True # yay, we have enough data
319 self._pcap_reader.f.seek(orig_pos, 0) # restore original position
322 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
324 Wait for next packet captured with a timeout
326 :param timeout: How long to wait for the packet
328 :returns: Captured packet if no packet arrived within timeout
329 :raises Exception: if no packet arrives within timeout
331 deadline = time.time() + timeout
332 if self._pcap_reader is None:
333 if not self.wait_for_capture_file(timeout):
334 raise CaptureTimeoutError("Capture file %s did not appear "
335 "within timeout" % self.out_path)
336 while time.time() < deadline:
338 self._pcap_reader = PcapReader(self.out_path)
341 self.test.logger.debug(
342 "Exception in scapy.PcapReader(%s): %s" %
343 (self.out_path, format_exc()))
344 if not self._pcap_reader:
345 raise CaptureTimeoutError("Capture file %s did not appear within "
346 "timeout" % self.out_path)
350 self.test.logger.debug("Waiting for packet")
353 self.test.logger.debug("Polling for packet")
354 while time.time() < deadline or poll:
355 if not self.verify_enough_packet_data_in_pcap():
356 time.sleep(0) # yield
359 p = self._pcap_reader.recv()
361 if filter_out_fn is not None and filter_out_fn(p):
362 self.test.logger.debug(
363 "Packet received after %ss was filtered out" %
364 (time.time() - (deadline - timeout)))
366 self.test.logger.debug(
367 "Packet received after %fs" %
368 (time.time() - (deadline - timeout)))
370 time.sleep(0) # yield
372 self.test.logger.debug("Timeout - no packets received")
373 raise CaptureTimeoutError("Packet didn't arrive within timeout")
375 def create_arp_req(self):
376 """Create ARP request applicable for this interface"""
377 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
378 ARP(op=ARP.who_has, pdst=self.local_ip4,
379 psrc=self.remote_ip4, hwsrc=self.remote_mac))
381 def create_ndp_req(self):
382 """Create NDP - NS applicable for this interface"""
383 nsma = in6_getnsma(inet_pton(socket.AF_INET6, self.local_ip6))
384 d = inet_ntop(socket.AF_INET6, nsma)
386 return (Ether(dst=in6_getnsmac(nsma)) /
387 IPv6(dst=d, src=self.remote_ip6) /
388 ICMPv6ND_NS(tgt=self.local_ip6) /
389 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
391 def resolve_arp(self, pg_interface=None):
392 """Resolve ARP using provided packet-generator interface
394 :param pg_interface: interface used to resolve, if None then this
398 if pg_interface is None:
400 self.test.logger.info("Sending ARP request for %s on port %s" %
401 (self.local_ip4, pg_interface.name))
402 arp_req = self.create_arp_req()
403 pg_interface.add_stream(arp_req)
404 pg_interface.enable_capture()
406 self.test.logger.info(self.test.vapi.cli("show trace"))
408 captured_packet = pg_interface.wait_for_packet(1)
410 self.test.logger.info("No ARP received on port %s" %
413 arp_reply = captured_packet.copy() # keep original for exception
414 # Make Dot1AD packet content recognizable to scapy
415 if arp_reply.type == 0x88a8:
416 arp_reply.type = 0x8100
417 arp_reply = Ether(str(arp_reply))
419 if arp_reply[ARP].op == ARP.is_at:
420 self.test.logger.info("VPP %s MAC address is %s " %
421 (self.name, arp_reply[ARP].hwsrc))
422 self._local_mac = arp_reply[ARP].hwsrc
424 self.test.logger.info("No ARP received on port %s" %
427 self.test.logger.error(
428 ppp("Unexpected response to ARP request:", captured_packet))
431 def resolve_ndp(self, pg_interface=None, timeout=1):
432 """Resolve NDP using provided packet-generator interface
434 :param pg_interface: interface used to resolve, if None then this
436 :param timeout: how long to wait for response before giving up
439 if pg_interface is None:
441 self.test.logger.info("Sending NDP request for %s on port %s" %
442 (self.local_ip6, pg_interface.name))
443 ndp_req = self.create_ndp_req()
444 pg_interface.add_stream(ndp_req)
445 pg_interface.enable_capture()
448 deadline = now + timeout
449 # Enabling IPv6 on an interface can generate more than the
450 # ND reply we are looking for (namely MLD). So loop through
451 # the replies to look for want we want.
452 while now < deadline:
454 captured_packet = pg_interface.wait_for_packet(
455 deadline - now, filter_out_fn=None)
457 self.test.logger.error(
458 "Timeout while waiting for NDP response")
460 ndp_reply = captured_packet.copy() # keep original for exception
461 # Make Dot1AD packet content recognizable to scapy
462 if ndp_reply.type == 0x88a8:
463 ndp_reply.type = 0x8100
464 ndp_reply = Ether(str(ndp_reply))
466 ndp_na = ndp_reply[ICMPv6ND_NA]
467 opt = ndp_na[ICMPv6NDOptDstLLAddr]
468 self.test.logger.info("VPP %s MAC address is %s " %
469 (self.name, opt.lladdr))
470 self._local_mac = opt.lladdr
471 self.test.logger.debug(self.test.vapi.cli("show trace"))
472 # we now have the MAC we've been after
475 self.test.logger.info(
476 ppp("Unexpected response to NDP request:",
480 self.test.logger.debug(self.test.vapi.cli("show trace"))
481 raise Exception("Timeout while waiting for NDP response")