4 from traceback import format_exc
5 from scapy.utils import wrpcap, rdpcap, PcapReader
6 from vpp_interface import VppInterface
8 from scapy.layers.l2 import Ether, ARP
9 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
10 ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
12 from util import ppp, ppc
13 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
14 from scapy.utils import inet_pton, inet_ntop
17 """ Is packet one of uninteresting IPv6 broadcasts? """
18 if p.haslayer(ICMPv6ND_RA):
19 if in6_ismaddr(p[IPv6].dst):
21 if p.haslayer(IPv6ExtHdrHopByHop):
22 for o in p[IPv6ExtHdrHopByHop].options:
23 if isinstance(o, RouterAlert):
28 class VppPGInterface(VppInterface):
30 VPP packet-generator interface
35 """packet-generator interface index assigned by VPP"""
40 """pcap file path - captured packets"""
45 """ pcap file path - injected packets"""
49 def capture_cli(self):
50 """CLI string to start capture on this interface"""
51 return self._capture_cli
55 """capture name for this interface"""
60 """CLI string to load the injected packets"""
61 return self._input_cli
64 def in_history_counter(self):
65 """Self-incrementing counter used when renaming old pcap files"""
66 v = self._in_history_counter
67 self._in_history_counter += 1
71 def out_history_counter(self):
72 """Self-incrementing counter used when renaming old pcap files"""
73 v = self._out_history_counter
74 self._out_history_counter += 1
77 def __init__(self, test, pg_index):
78 """ Create VPP packet-generator interface """
79 r = test.vapi.pg_create_interface(pg_index)
80 self._sw_if_index = r.sw_if_index
82 super(VppPGInterface, self).__init__(test)
84 self._in_history_counter = 0
85 self._out_history_counter = 0
86 self._pg_index = pg_index
87 self._out_file = "pg%u_out.pcap" % self.pg_index
88 self._out_path = self.test.tempdir + "/" + self._out_file
89 self._in_file = "pg%u_in.pcap" % self.pg_index
90 self._in_path = self.test.tempdir + "/" + self._in_file
91 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
92 self.pg_index, self.out_path)
93 self._cap_name = "pcap%u" % self.sw_if_index
94 self._input_cli = "packet-generator new pcap %s source pg%u name %s" % (
95 self.in_path, self.pg_index, self.cap_name)
97 def rotate_out_file(self):
99 if os.path.isfile(self.out_path):
100 os.rename(self.out_path,
101 "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
105 self.out_history_counter,
110 def enable_capture(self):
111 """ Enable capture on this packet-generator interface"""
112 self.rotate_out_file()
113 # FIXME this should be an API, but no such exists atm
114 self.test.vapi.cli(self.capture_cli)
115 self._pcap_reader = None
117 def add_stream(self, pkts):
119 Add a stream of packets to this packet-generator
121 :param pkts: iterable packets
125 if os.path.isfile(self.in_path):
126 os.rename(self.in_path,
127 "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
131 self.in_history_counter,
135 wrpcap(self.in_path, pkts)
136 self.test.register_capture(self.cap_name)
137 # FIXME this should be an API, but no such exists atm
138 self.test.vapi.cli(self.input_cli)
140 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
141 """ Helper method to get capture and filter it """
143 if not self.wait_for_capture_file(timeout):
145 output = rdpcap(self.out_path)
146 self.test.logger.debug("Capture has %s packets" % len(output.res))
148 self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
149 (self.out_path, format_exc()))
151 before = len(output.res)
153 output.res = [p for p in output.res if not filter_out_fn(p)]
154 removed = before - len(output.res)
156 self.test.logger.debug(
157 "Filtered out %s packets from capture (returning %s)" %
158 (removed, len(output.res)))
161 def get_capture(self, expected_count=None, remark=None, timeout=1,
162 filter_out_fn=is_ipv6_misc):
163 """ Get captured packets
165 :param expected_count: expected number of packets to capture, if None,
166 then self.test.packet_count_for_dst_pg_idx is
167 used to lookup the expected count
168 :param remark: remark printed into debug logs
169 :param timeout: how long to wait for packets
170 :param filter_out_fn: filter applied to each packet, packets for which
171 the filter returns True are removed from capture
172 :returns: iterable packets
174 remaining_time = timeout
176 name = self.name if remark is None else "%s (%s)" % (self.name, remark)
177 based_on = "based on provided argument"
178 if expected_count is None:
180 self.test.get_packet_count_for_if_idx(self.sw_if_index)
181 based_on = "based on stored packet_infos"
182 if expected_count == 0:
184 "Internal error, expected packet count for %s is 0!" % name)
185 self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
186 expected_count, based_on, name))
187 while remaining_time > 0:
189 capture = self._get_capture(remaining_time, filter_out_fn)
190 elapsed_time = time.time() - before
192 if len(capture.res) == expected_count:
193 # bingo, got the packets we expected
195 elif expected_count == 0:
197 remaining_time -= elapsed_time
199 raise Exception("Captured packets mismatch, captured %s packets, "
200 "expected %s packets on %s" %
201 (len(capture.res), expected_count, name))
203 raise Exception("No packets captured on %s" % name)
205 def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
206 """ Assert that nothing unfiltered was captured on interface
208 :param remark: remark printed into debug logs
209 :param filter_out_fn: filter applied to each packet, packets for which
210 the filter returns True are removed from capture
212 if os.path.isfile(self.out_path):
214 capture = self.get_capture(
215 0, remark=remark, filter_out_fn=filter_out_fn)
217 # junk filtered out, we're good
219 self.test.logger.error(
220 ppc("Unexpected packets captured:", capture))
224 raise AssertionError(
225 "Non-empty capture file present for interface %s (%s)" %
228 raise AssertionError("Capture file present for interface %s" %
231 def wait_for_capture_file(self, timeout=1):
233 Wait until pcap capture file appears
235 :param timeout: How long to wait for the packet (default 1s)
237 :returns: True/False if the file is present or appears within timeout
239 limit = time.time() + timeout
240 if not os.path.isfile(self.out_path):
241 self.test.logger.debug("Waiting for capture file %s to appear, "
242 "timeout is %ss" % (self.out_path, timeout))
244 self.test.logger.debug("Capture file %s already exists" %
247 while time.time() < limit:
248 if os.path.isfile(self.out_path):
250 time.sleep(0) # yield
251 if os.path.isfile(self.out_path):
252 self.test.logger.debug("Capture file appeared after %fs" %
253 (time.time() - (limit - timeout)))
255 self.test.logger.debug("Timeout - capture file still nowhere")
259 def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
261 Wait for next packet captured with a timeout
263 :param timeout: How long to wait for the packet
265 :returns: Captured packet if no packet arrived within timeout
266 :raises Exception: if no packet arrives within timeout
268 deadline = time.time() + timeout
269 if self._pcap_reader is None:
270 if not self.wait_for_capture_file(timeout):
271 raise Exception("Capture file %s did not appear within "
272 "timeout" % self.out_path)
273 while time.time() < deadline:
275 self._pcap_reader = PcapReader(self.out_path)
278 self.test.logger.debug("Exception in scapy.PcapReader(%s): "
279 "%s" % (self.out_path, format_exc()))
280 if not self._pcap_reader:
281 raise Exception("Capture file %s did not appear within "
282 "timeout" % self.out_path)
284 self.test.logger.debug("Waiting for packet")
285 while time.time() < deadline:
286 p = self._pcap_reader.recv()
288 if filter_out_fn is not None and filter_out_fn(p):
289 self.test.logger.debug(
290 "Packet received after %ss was filtered out" %
291 (time.time() - (deadline - timeout)))
293 self.test.logger.debug("Packet received after %fs" %
294 (time.time() - (deadline - timeout)))
296 time.sleep(0) # yield
297 self.test.logger.debug("Timeout - no packets received")
298 raise Exception("Packet didn't arrive within timeout")
300 def create_arp_req(self):
301 """Create ARP request applicable for this interface"""
302 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
303 ARP(op=ARP.who_has, pdst=self.local_ip4,
304 psrc=self.remote_ip4, hwsrc=self.remote_mac))
306 def create_ndp_req(self):
307 """Create NDP - NS applicable for this interface"""
308 nsma = in6_getnsma(inet_pton(socket.AF_INET6, self.local_ip6))
309 d = inet_ntop(socket.AF_INET6, nsma)
311 return (Ether(dst=in6_getnsmac(nsma)) /
312 IPv6(dst=d, src=self.remote_ip6) /
313 ICMPv6ND_NS(tgt=self.local_ip6) /
314 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
316 def resolve_arp(self, pg_interface=None):
317 """Resolve ARP using provided packet-generator interface
319 :param pg_interface: interface used to resolve, if None then this
323 if pg_interface is None:
325 self.test.logger.info("Sending ARP request for %s on port %s" %
326 (self.local_ip4, pg_interface.name))
327 arp_req = self.create_arp_req()
328 pg_interface.add_stream(arp_req)
329 pg_interface.enable_capture()
331 self.test.logger.info(self.test.vapi.cli("show trace"))
333 captured_packet = pg_interface.wait_for_packet(1)
335 self.test.logger.info("No ARP received on port %s" %
338 self.rotate_out_file()
339 arp_reply = captured_packet.copy() # keep original for exception
340 # Make Dot1AD packet content recognizable to scapy
341 if arp_reply.type == 0x88a8:
342 arp_reply.type = 0x8100
343 arp_reply = Ether(str(arp_reply))
345 if arp_reply[ARP].op == ARP.is_at:
346 self.test.logger.info("VPP %s MAC address is %s " %
347 (self.name, arp_reply[ARP].hwsrc))
348 self._local_mac = arp_reply[ARP].hwsrc
350 self.test.logger.info("No ARP received on port %s" %
353 self.test.logger.error(
354 ppp("Unexpected response to ARP request:", captured_packet))
357 def resolve_ndp(self, pg_interface=None, timeout=1):
358 """Resolve NDP using provided packet-generator interface
360 :param pg_interface: interface used to resolve, if None then this
362 :param timeout: how long to wait for response before giving up
365 if pg_interface is None:
367 self.test.logger.info("Sending NDP request for %s on port %s" %
368 (self.local_ip6, pg_interface.name))
369 ndp_req = self.create_ndp_req()
370 pg_interface.add_stream(ndp_req)
371 pg_interface.enable_capture()
374 deadline = now + timeout
375 # Enabling IPv6 on an interface can generate more than the
376 # ND reply we are looking for (namely MLD). So loop through
377 # the replies to look for want we want.
378 while now < deadline:
380 captured_packet = pg_interface.wait_for_packet(
381 deadline - now, filter_out_fn=None)
383 self.test.logger.error("Timeout while waiting for NDP response")
385 ndp_reply = captured_packet.copy() # keep original for exception
386 # Make Dot1AD packet content recognizable to scapy
387 if ndp_reply.type == 0x88a8:
388 ndp_reply.type = 0x8100
389 ndp_reply = Ether(str(ndp_reply))
391 ndp_na = ndp_reply[ICMPv6ND_NA]
392 opt = ndp_na[ICMPv6NDOptDstLLAddr]
393 self.test.logger.info("VPP %s MAC address is %s " %
394 (self.name, opt.lladdr))
395 self._local_mac = opt.lladdr
396 self.test.logger.debug(self.test.vapi.cli("show trace"))
397 # we now have the MAC we've been after
398 self.rotate_out_file()
401 self.test.logger.info(
402 ppp("Unexpected response to NDP request:", captured_packet))
405 self.test.logger.debug(self.test.vapi.cli("show trace"))
406 self.rotate_out_file()
407 raise Exception("Timeout while waiting for NDP response")