3 from scapy.utils import wrpcap, rdpcap, PcapReader
4 from vpp_interface import VppInterface
6 from scapy.layers.l2 import Ether, ARP
7 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
8 ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
10 from util import ppp, ppc
14 """ Is packet one of uninteresting IPv6 broadcasts? """
15 if p.haslayer(ICMPv6ND_RA):
17 if p.haslayer(IPv6ExtHdrHopByHop):
18 for o in p[IPv6ExtHdrHopByHop].options:
19 if isinstance(o, RouterAlert):
24 class VppPGInterface(VppInterface):
26 VPP packet-generator interface
31 """packet-generator interface index assigned by VPP"""
36 """pcap file path - captured packets"""
41 """ pcap file path - injected packets"""
45 def capture_cli(self):
46 """CLI string to start capture on this interface"""
47 return self._capture_cli
51 """capture name for this interface"""
56 """CLI string to load the injected packets"""
57 return self._input_cli
60 def in_history_counter(self):
61 """Self-incrementing counter used when renaming old pcap files"""
62 v = self._in_history_counter
63 self._in_history_counter += 1
67 def out_history_counter(self):
68 """Self-incrementing counter used when renaming old pcap files"""
69 v = self._out_history_counter
70 self._out_history_counter += 1
73 def __init__(self, test, pg_index):
74 """ Create VPP packet-generator interface """
75 r = test.vapi.pg_create_interface(pg_index)
76 self._sw_if_index = r.sw_if_index
78 super(VppPGInterface, self).__init__(test)
80 self._in_history_counter = 0
81 self._out_history_counter = 0
82 self._pg_index = pg_index
83 self._out_file = "pg%u_out.pcap" % self.pg_index
84 self._out_path = self.test.tempdir + "/" + self._out_file
85 self._in_file = "pg%u_in.pcap" % self.pg_index
86 self._in_path = self.test.tempdir + "/" + self._in_file
87 self._capture_cli = "packet-generator capture pg%u pcap %s" % (
88 self.pg_index, self.out_path)
89 self._cap_name = "pcap%u" % self.sw_if_index
90 self._input_cli = "packet-generator new pcap %s source pg%u name %s" % (
91 self.in_path, self.pg_index, self.cap_name)
93 def enable_capture(self):
94 """ Enable capture on this packet-generator interface"""
96 if os.path.isfile(self.out_path):
97 os.rename(self.out_path,
98 "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
102 self.out_history_counter,
106 # FIXME this should be an API, but no such exists atm
107 self.test.vapi.cli(self.capture_cli)
108 self._pcap_reader = None
110 def add_stream(self, pkts):
112 Add a stream of packets to this packet-generator
114 :param pkts: iterable packets
118 if os.path.isfile(self.in_path):
119 os.rename(self.in_path,
120 "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
124 self.in_history_counter,
128 wrpcap(self.in_path, pkts)
129 self.test.register_capture(self.cap_name)
130 # FIXME this should be an API, but no such exists atm
131 self.test.vapi.cli(self.input_cli)
133 def get_capture(self, remark=None, filter_fn=is_ipv6_misc):
137 :param remark: remark printed into debug logs
138 :param filter_fn: filter applied to each packet, packets for which
139 the filter returns True are removed from capture
140 :returns: iterable packets
143 self.wait_for_capture_file()
144 output = rdpcap(self.out_path)
145 self.test.logger.debug("Capture has %s packets" % len(output.res))
146 except IOError: # TODO
147 self.test.logger.debug("File %s does not exist, probably because no"
148 " packets arrived" % self.out_path)
150 raise Exception("No packets captured on %s(%s)" %
153 raise Exception("No packets captured on %s" % self.name)
154 before = len(output.res)
156 output.res = [p for p in output.res if not filter_fn(p)]
157 removed = len(output.res) - before
159 self.test.logger.debug(
160 "Filtered out %s packets from capture (returning %s)" %
161 (removed, len(output.res)))
164 def assert_nothing_captured(self, remark=None):
165 if os.path.isfile(self.out_path):
167 capture = self.get_capture(remark=remark)
168 self.test.logger.error(
169 ppc("Unexpected packets captured:", capture))
173 raise AssertionError(
174 "Capture file present for interface %s(%s)" %
177 raise AssertionError("Capture file present for interface %s" %
180 def wait_for_capture_file(self, timeout=1):
182 Wait until pcap capture file appears
184 :param timeout: How long to wait for the packet (default 1s)
186 :raises Exception: if the capture file does not appear within timeout
188 limit = time.time() + timeout
189 if not os.path.isfile(self.out_path):
190 self.test.logger.debug(
191 "Waiting for capture file to appear, timeout is %ss", timeout)
193 self.test.logger.debug("Capture file already exists")
195 while time.time() < limit:
196 if os.path.isfile(self.out_path):
198 time.sleep(0) # yield
199 if os.path.isfile(self.out_path):
200 self.test.logger.debug("Capture file appeared after %fs" %
201 (time.time() - (limit - timeout)))
203 self.test.logger.debug("Timeout - capture file still nowhere")
204 raise Exception("Capture file did not appear within timeout")
206 def wait_for_packet(self, timeout):
208 Wait for next packet captured with a timeout
210 :param timeout: How long to wait for the packet
212 :returns: Captured packet if no packet arrived within timeout
213 :raises Exception: if no packet arrives within timeout
215 limit = time.time() + timeout
216 if self._pcap_reader is None:
217 self.wait_for_capture_file(timeout)
218 self._pcap_reader = PcapReader(self.out_path)
220 self.test.logger.debug("Waiting for packet")
221 while time.time() < limit:
222 p = self._pcap_reader.recv()
224 self.test.logger.debug("Packet received after %fs",
225 (time.time() - (limit - timeout)))
227 time.sleep(0) # yield
228 self.test.logger.debug("Timeout - no packets received")
229 raise Exception("Packet didn't arrive within timeout")
231 def create_arp_req(self):
232 """Create ARP request applicable for this interface"""
233 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
234 ARP(op=ARP.who_has, pdst=self.local_ip4,
235 psrc=self.remote_ip4, hwsrc=self.remote_mac))
237 def create_ndp_req(self):
238 """Create NDP - NS applicable for this interface"""
239 return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
240 IPv6(src=self.remote_ip6, dst=self.local_ip6) /
241 ICMPv6ND_NS(tgt=self.local_ip6) /
242 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
244 def resolve_arp(self, pg_interface=None):
245 """Resolve ARP using provided packet-generator interface
247 :param pg_interface: interface used to resolve, if None then this
251 if pg_interface is None:
253 self.test.logger.info("Sending ARP request for %s on port %s" %
254 (self.local_ip4, pg_interface.name))
255 arp_req = self.create_arp_req()
256 pg_interface.add_stream(arp_req)
257 pg_interface.enable_capture()
259 self.test.logger.info(self.test.vapi.cli("show trace"))
261 arp_reply = pg_interface.get_capture(filter_fn=None)
263 self.test.logger.info("No ARP received on port %s" %
266 arp_reply = arp_reply[0]
267 # Make Dot1AD packet content recognizable to scapy
268 if arp_reply.type == 0x88a8:
269 arp_reply.type = 0x8100
270 arp_reply = Ether(str(arp_reply))
272 if arp_reply[ARP].op == ARP.is_at:
273 self.test.logger.info("VPP %s MAC address is %s " %
274 (self.name, arp_reply[ARP].hwsrc))
275 self._local_mac = arp_reply[ARP].hwsrc
277 self.test.logger.info(
278 "No ARP received on port %s" %
281 self.test.logger.error(
282 ppp("Unexpected response to ARP request:", arp_reply))
285 def resolve_ndp(self, pg_interface=None):
286 """Resolve NDP using provided packet-generator interface
288 :param pg_interface: interface used to resolve, if None then this
292 if pg_interface is None:
294 self.test.logger.info("Sending NDP request for %s on port %s" %
295 (self.local_ip6, pg_interface.name))
296 ndp_req = self.create_ndp_req()
297 pg_interface.add_stream(ndp_req)
298 pg_interface.enable_capture()
300 self.test.logger.info(self.test.vapi.cli("show trace"))
301 replies = pg_interface.get_capture(filter_fn=None)
302 if replies is None or len(replies) == 0:
303 self.test.logger.info(
304 "No NDP received on port %s" %
307 # Enabling IPv6 on an interface can generate more than the
308 # ND reply we are looking for (namely MLD). So loop through
309 # the replies to look for want we want.
310 for ndp_reply in replies:
311 # Make Dot1AD packet content recognizable to scapy
312 if ndp_reply.type == 0x88a8:
313 ndp_reply.type = 0x8100
314 ndp_reply = Ether(str(ndp_reply))
316 ndp_na = ndp_reply[ICMPv6ND_NA]
317 opt = ndp_na[ICMPv6NDOptDstLLAddr]
318 self.test.logger.info("VPP %s MAC address is %s " %
319 (self.name, opt.lladdr))
320 self._local_mac = opt.lladdr
322 self.test.logger.info(
323 ppp("Unexpected response to NDP request:", ndp_reply))
324 # if no packets above provided the local MAC, then this failed.
325 if not hasattr(self, '_local_mac'):